1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
15#include "SystemZConstantPoolValue.h"
16#include "SystemZMachineFunctionInfo.h"
17#include "SystemZTargetMachine.h"
18#include "llvm/CodeGen/CallingConvLower.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/IntrinsicsS390.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/KnownBits.h"
27#include <cctype>
28
29using namespace llvm;
30
31#define DEBUG_TYPE "systemz-lower"
32
33namespace {
34// Represents information about a comparison.
35struct Comparison {
36 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
37 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
38 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
39
40 // The operands to the comparison.
41 SDValue Op0, Op1;
42
43 // Chain if this is a strict floating-point comparison.
44 SDValue Chain;
45
46 // The opcode that should be used to compare Op0 and Op1.
47 unsigned Opcode;
48
49 // A SystemZICMP value. Only used for integer comparisons.
50 unsigned ICmpType;
51
52 // The mask of CC values that Opcode can produce.
53 unsigned CCValid;
54
55 // The mask of CC values for which the original condition is true.
56 unsigned CCMask;
57};
58} // end anonymous namespace
59
60// Classify VT as either 32 or 64 bit.
61static bool is32Bit(EVT VT) {
62 switch (VT.getSimpleVT().SimpleTy) {
63 case MVT::i32:
64 return true;
65 case MVT::i64:
66 return false;
67 default:
68 llvm_unreachable("Unsupported type");
69 }
70}
71
72// Return a version of MachineOperand that can be safely used before the
73// final use.
74static MachineOperand earlyUseOperand(MachineOperand Op) {
75 if (Op.isReg())
76 Op.setIsKill(false);
77 return Op;
78}
79
80SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
81 const SystemZSubtarget &STI)
82 : TargetLowering(TM), Subtarget(STI) {
83 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize(0));
84
85 // Set up the register classes.
86 if (Subtarget.hasHighWord())
87 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
88 else
89 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
90 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
91 if (!useSoftFloat()) {
92 if (Subtarget.hasVector()) {
93 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
94 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
95 } else {
96 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
97 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
98 }
99 if (Subtarget.hasVectorEnhancements1())
100 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
101 else
102 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
103
104 if (Subtarget.hasVector()) {
105 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
106 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
107 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
108 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
109 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
110 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
111 }
112 }
113
114 // Compute derived properties from the register classes
115 computeRegisterProperties(Subtarget.getRegisterInfo());
116
117 // Set up special registers.
118 setStackPointerRegisterToSaveRestore(SystemZ::R15D);
119
120 // TODO: It may be better to default to latency-oriented scheduling, however
121 // LLVM's current latency-oriented scheduler can't handle physreg definitions
122 // such as SystemZ has with CC, so set this to the register-pressure
123 // scheduler, because it can.
124 setSchedulingPreference(Sched::RegPressure);
125
126 setBooleanContents(ZeroOrOneBooleanContent);
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129 // Instructions are strings of 2-byte aligned 2-byte values.
130 setMinFunctionAlignment(Align(2));
131 // For performance reasons we prefer 16-byte alignment.
132 setPrefFunctionAlignment(Align(16));
133
134 // Handle operations that are handled in a similar way for all types.
135 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
136 I <= MVT::LAST_FP_VALUETYPE;
137 ++I) {
138 MVT VT = MVT::SimpleValueType(I);
139 if (isTypeLegal(VT)) {
140 // Lower SET_CC into an IPM-based sequence.
141 setOperationAction(ISD::SETCC, VT, Custom);
142 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
143 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
144
145 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
146 setOperationAction(ISD::SELECT, VT, Expand);
147
148 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
149 setOperationAction(ISD::SELECT_CC, VT, Custom);
150 setOperationAction(ISD::BR_CC, VT, Custom);
151 }
152 }
153
154 // Expand jump table branches as address arithmetic followed by an
155 // indirect jump.
156 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
157
158 // Expand BRCOND into a BR_CC (see above).
159 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
160
161 // Handle integer types.
162 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
163 I <= MVT::LAST_INTEGER_VALUETYPE;
164 ++I) {
165 MVT VT = MVT::SimpleValueType(I);
166 if (isTypeLegal(VT)) {
167 setOperationAction(ISD::ABS, VT, Legal);
168
169 // Expand individual DIV and REMs into DIVREMs.
170 setOperationAction(ISD::SDIV, VT, Expand);
171 setOperationAction(ISD::UDIV, VT, Expand);
172 setOperationAction(ISD::SREM, VT, Expand);
173 setOperationAction(ISD::UREM, VT, Expand);
174 setOperationAction(ISD::SDIVREM, VT, Custom);
175 setOperationAction(ISD::UDIVREM, VT, Custom);
176
177 // Support addition/subtraction with overflow.
178 setOperationAction(ISD::SADDO, VT, Custom);
179 setOperationAction(ISD::SSUBO, VT, Custom);
180
181 // Support addition/subtraction with carry.
182 setOperationAction(ISD::UADDO, VT, Custom);
183 setOperationAction(ISD::USUBO, VT, Custom);
184
185 // Support carry in as value rather than glue.
186 setOperationAction(ISD::ADDCARRY, VT, Custom);
187 setOperationAction(ISD::SUBCARRY, VT, Custom);
188
189 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
190 // stores, putting a serialization instruction after the stores.
191 setOperationAction(ISD::ATOMIC_LOAD, VT, Custom);
192 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
193
194 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
195 // available, or if the operand is constant.
196 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
197
198 // Use POPCNT on z196 and above.
199 if (Subtarget.hasPopulationCount())
200 setOperationAction(ISD::CTPOP, VT, Custom);
201 else
202 setOperationAction(ISD::CTPOP, VT, Expand);
203
204 // No special instructions for these.
205 setOperationAction(ISD::CTTZ, VT, Expand);
206 setOperationAction(ISD::ROTR, VT, Expand);
207
208 // Use *MUL_LOHI where possible instead of MULH*.
209 setOperationAction(ISD::MULHS, VT, Expand);
210 setOperationAction(ISD::MULHU, VT, Expand);
211 setOperationAction(ISD::SMUL_LOHI, VT, Custom);
212 setOperationAction(ISD::UMUL_LOHI, VT, Custom);
213
214 // Only z196 and above have native support for conversions to unsigned.
215 // On z10, promoting to i64 doesn't generate an inexact condition for
216 // values that are outside the i32 range but in the i64 range, so use
217 // the default expansion.
218 if (!Subtarget.hasFPExtension())
219 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
220
221 // Mirror those settings for STRICT_FP_TO_[SU]INT. Note that these all
222 // default to Expand, so need to be modified to Legal where appropriate.
223 setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Legal);
224 if (Subtarget.hasFPExtension())
225 setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Legal);
226
227 // And similarly for STRICT_[SU]INT_TO_FP.
228 setOperationAction(ISD::STRICT_SINT_TO_FP, VT, Legal);
229 if (Subtarget.hasFPExtension())
230 setOperationAction(ISD::STRICT_UINT_TO_FP, VT, Legal);
231 }
232 }
233
234 // Type legalization will convert 8- and 16-bit atomic operations into
235 // forms that operate on i32s (but still keeping the original memory VT).
236 // Lower them into full i32 operations.
237 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom);
238 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom);
239 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
240 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
241 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom);
242 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom);
243 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
244 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom);
245 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom);
246 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
247 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
248
249 // Even though i128 is not a legal type, we still need to custom lower
250 // the atomic operations in order to exploit SystemZ instructions.
251 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
252 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
253
254 // We can use the CC result of compare-and-swap to implement
255 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
256 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Custom);
257 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Custom);
258 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
259
260 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
261
262 // Traps are legal, as we will convert them to "j .+2".
263 setOperationAction(ISD::TRAP, MVT::Other, Legal);
264
265 // z10 has instructions for signed but not unsigned FP conversion.
266 // Handle unsigned 32-bit types as signed 64-bit types.
267 if (!Subtarget.hasFPExtension()) {
268 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
269 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
270 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Promote);
271 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
272 }
273
274 // We have native support for a 64-bit CTLZ, via FLOGR.
275 setOperationAction(ISD::CTLZ, MVT::i32, Promote);
276 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Promote);
277 setOperationAction(ISD::CTLZ, MVT::i64, Legal);
278
279 // On z15 we have native support for a 64-bit CTPOP.
280 if (Subtarget.hasMiscellaneousExtensions3()) {
281 setOperationAction(ISD::CTPOP, MVT::i32, Promote);
282 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
283 }
284
285 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
286 setOperationAction(ISD::OR, MVT::i64, Custom);
287
288 // FIXME: Can we support these natively?
289 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
290 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
291 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
292
293 // We have native instructions for i8, i16 and i32 extensions, but not i1.
294 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
295 for (MVT VT : MVT::integer_valuetypes()) {
296 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
297 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
298 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
299 }
300
301 // Handle the various types of symbolic address.
302 setOperationAction(ISD::ConstantPool, PtrVT, Custom);
303 setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
304 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
305 setOperationAction(ISD::BlockAddress, PtrVT, Custom);
306 setOperationAction(ISD::JumpTable, PtrVT, Custom);
307
308 // We need to handle dynamic allocations specially because of the
309 // 160-byte area at the bottom of the stack.
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
311 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
312
313 // Use custom expanders so that we can force the function to use
314 // a frame pointer.
315 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
316 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
317
318 // Handle prefetches with PFD or PFDRL.
319 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
320
321 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
322 // Assume by default that all vector operations need to be expanded.
323 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
324 if (getOperationAction(Opcode, VT) == Legal)
325 setOperationAction(Opcode, VT, Expand);
326
327 // Likewise all truncating stores and extending loads.
328 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
329 setTruncStoreAction(VT, InnerVT, Expand);
330 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
331 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
332 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
333 }
334
335 if (isTypeLegal(VT)) {
336 // These operations are legal for anything that can be stored in a
337 // vector register, even if there is no native support for the format
338 // as such. In particular, we can do these for v4f32 even though there
339 // are no specific instructions for that format.
340 setOperationAction(ISD::LOAD, VT, Legal);
341 setOperationAction(ISD::STORE, VT, Legal);
342 setOperationAction(ISD::VSELECT, VT, Legal);
343 setOperationAction(ISD::BITCAST, VT, Legal);
344 setOperationAction(ISD::UNDEF, VT, Legal);
345
346 // Likewise, except that we need to replace the nodes with something
347 // more specific.
348 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
349 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
350 }
351 }
352
353 // Handle integer vector types.
354 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
355 if (isTypeLegal(VT)) {
356 // These operations have direct equivalents.
357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
358 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
359 setOperationAction(ISD::ADD, VT, Legal);
360 setOperationAction(ISD::SUB, VT, Legal);
361 if (VT != MVT::v2i64)
362 setOperationAction(ISD::MUL, VT, Legal);
363 setOperationAction(ISD::ABS, VT, Legal);
364 setOperationAction(ISD::AND, VT, Legal);
365 setOperationAction(ISD::OR, VT, Legal);
366 setOperationAction(ISD::XOR, VT, Legal);
367 if (Subtarget.hasVectorEnhancements1())
368 setOperationAction(ISD::CTPOP, VT, Legal);
369 else
370 setOperationAction(ISD::CTPOP, VT, Custom);
371 setOperationAction(ISD::CTTZ, VT, Legal);
372 setOperationAction(ISD::CTLZ, VT, Legal);
373
374 // Convert a GPR scalar to a vector by inserting it into element 0.
375 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
376
377 // Use a series of unpacks for extensions.
378 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
379 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
380
381 // Detect shifts by a scalar amount and convert them into
382 // V*_BY_SCALAR.
383 setOperationAction(ISD::SHL, VT, Custom);
384 setOperationAction(ISD::SRA, VT, Custom);
385 setOperationAction(ISD::SRL, VT, Custom);
386
387 // At present ROTL isn't matched by DAGCombiner. ROTR should be
388 // converted into ROTL.
389 setOperationAction(ISD::ROTL, VT, Expand);
390 setOperationAction(ISD::ROTR, VT, Expand);
391
392 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
393 // and inverting the result as necessary.
394 setOperationAction(ISD::SETCC, VT, Custom);
395 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
396 if (Subtarget.hasVectorEnhancements1())
397 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
398 }
399 }
400
401 if (Subtarget.hasVector()) {
402 // There should be no need to check for float types other than v2f64
403 // since <2 x f32> isn't a legal type.
404 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
405 setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal);
406 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
407 setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal);
408 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
409 setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal);
410 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
411 setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal);
412
413 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
414 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f64, Legal);
415 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
416 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f64, Legal);
417 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
418 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f64, Legal);
419 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
420 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f64, Legal);
421 }
422
423 if (Subtarget.hasVectorEnhancements2()) {
424 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
425 setOperationAction(ISD::FP_TO_SINT, MVT::v4f32, Legal);
426 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
427 setOperationAction(ISD::FP_TO_UINT, MVT::v4f32, Legal);
428 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
429 setOperationAction(ISD::SINT_TO_FP, MVT::v4f32, Legal);
430 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
431 setOperationAction(ISD::UINT_TO_FP, MVT::v4f32, Legal);
432
433 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
434 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f32, Legal);
435 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
436 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f32, Legal);
437 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
438 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f32, Legal);
439 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
440 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f32, Legal);
441 }
442
443 // Handle floating-point types.
444 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
445 I <= MVT::LAST_FP_VALUETYPE;
446 ++I) {
447 MVT VT = MVT::SimpleValueType(I);
448 if (isTypeLegal(VT)) {
449 // We can use FI for FRINT.
450 setOperationAction(ISD::FRINT, VT, Legal);
451
452 // We can use the extended form of FI for other rounding operations.
453 if (Subtarget.hasFPExtension()) {
454 setOperationAction(ISD::FNEARBYINT, VT, Legal);
455 setOperationAction(ISD::FFLOOR, VT, Legal);
456 setOperationAction(ISD::FCEIL, VT, Legal);
457 setOperationAction(ISD::FTRUNC, VT, Legal);
458 setOperationAction(ISD::FROUND, VT, Legal);
459 }
460
461 // No special instructions for these.
462 setOperationAction(ISD::FSIN, VT, Expand);
463 setOperationAction(ISD::FCOS, VT, Expand);
464 setOperationAction(ISD::FSINCOS, VT, Expand);
465 setOperationAction(ISD::FREM, VT, Expand);
466 setOperationAction(ISD::FPOW, VT, Expand);
467
468 // Handle constrained floating-point operations.
469 setOperationAction(ISD::STRICT_FADD, VT, Legal);
470 setOperationAction(ISD::STRICT_FSUB, VT, Legal);
471 setOperationAction(ISD::STRICT_FMUL, VT, Legal);
472 setOperationAction(ISD::STRICT_FDIV, VT, Legal);
473 setOperationAction(ISD::STRICT_FMA, VT, Legal);
474 setOperationAction(ISD::STRICT_FSQRT, VT, Legal);
475 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
476 setOperationAction(ISD::STRICT_FP_ROUND, VT, Legal);
477 setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal);
478 if (Subtarget.hasFPExtension()) {
479 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
480 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
481 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
482 setOperationAction(ISD::STRICT_FROUND, VT, Legal);
483 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
484 }
485 }
486 }
487
488 // Handle floating-point vector types.
489 if (Subtarget.hasVector()) {
490 // Scalar-to-vector conversion is just a subreg.
491 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
492 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
493
494 // Some insertions and extractions can be done directly but others
495 // need to go via integers.
496 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
497 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
498 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
499 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
500
501 // These operations have direct equivalents.
502 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
503 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
504 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
505 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
506 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
507 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
508 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
509 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
510 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
511 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
512 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
513 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
514 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
515 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
516
517 // Handle constrained floating-point operations.
518 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
519 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
520 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
521 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
522 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
523 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
524 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
525 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
526 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
527 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
528 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
529 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
530 }
531
532 // The vector enhancements facility 1 has instructions for these.
533 if (Subtarget.hasVectorEnhancements1()) {
534 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
535 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
536 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
537 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
538 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
539 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
540 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
541 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
542 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
543 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
544 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
545 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
546 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
547 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548
549 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
550 setOperationAction(ISD::FMAXIMUM, MVT::f64, Legal);
551 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
552 setOperationAction(ISD::FMINIMUM, MVT::f64, Legal);
553
554 setOperationAction(ISD::FMAXNUM, MVT::v2f64, Legal);
555 setOperationAction(ISD::FMAXIMUM, MVT::v2f64, Legal);
556 setOperationAction(ISD::FMINNUM, MVT::v2f64, Legal);
557 setOperationAction(ISD::FMINIMUM, MVT::v2f64, Legal);
558
559 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
560 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
561 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
562 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
563
564 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
565 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
566 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
567 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
568
569 setOperationAction(ISD::FMAXNUM, MVT::f128, Legal);
570 setOperationAction(ISD::FMAXIMUM, MVT::f128, Legal);
571 setOperationAction(ISD::FMINNUM, MVT::f128, Legal);
572 setOperationAction(ISD::FMINIMUM, MVT::f128, Legal);
573
574 // Handle constrained floating-point operations.
575 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
576 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
577 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
578 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
579 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
580 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
581 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
582 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
583 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
584 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
585 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
586 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
587 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
588 MVT::v4f32, MVT::v2f64 }) {
589 setOperationAction(ISD::STRICT_FMAXNUM, VT, Legal);
590 setOperationAction(ISD::STRICT_FMINNUM, VT, Legal);
591 setOperationAction(ISD::STRICT_FMAXIMUM, VT, Legal);
592 setOperationAction(ISD::STRICT_FMINIMUM, VT, Legal);
593 }
594 }
595
596 // We only have fused f128 multiply-addition on vector registers.
597 if (!Subtarget.hasVectorEnhancements1()) {
598 setOperationAction(ISD::FMA, MVT::f128, Expand);
599 setOperationAction(ISD::STRICT_FMA, MVT::f128, Expand);
600 }
601
602 // We don't have a copysign instruction on vector registers.
603 if (Subtarget.hasVectorEnhancements1())
604 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
605
606 // Needed so that we don't try to implement f128 constant loads using
607 // a load-and-extend of a f80 constant (in cases where the constant
608 // would fit in an f80).
609 for (MVT VT : MVT::fp_valuetypes())
610 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
611
612 // We don't have extending load instruction on vector registers.
613 if (Subtarget.hasVectorEnhancements1()) {
614 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
615 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
616 }
617
618 // Floating-point truncation and stores need to be done separately.
619 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
620 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
621 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
622
623 // We have 64-bit FPR<->GPR moves, but need special handling for
624 // 32-bit forms.
625 if (!Subtarget.hasVector()) {
626 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
627 setOperationAction(ISD::BITCAST, MVT::f32, Custom);
628 }
629
630 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
631 // structure, but VAEND is a no-op.
632 setOperationAction(ISD::VASTART, MVT::Other, Custom);
633 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
634 setOperationAction(ISD::VAEND, MVT::Other, Expand);
635
636 // Codes for which we want to perform some z-specific combinations.
637 setTargetDAGCombine(ISD::ZERO_EXTEND);
638 setTargetDAGCombine(ISD::SIGN_EXTEND);
639 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
640 setTargetDAGCombine(ISD::LOAD);
641 setTargetDAGCombine(ISD::STORE);
642 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
643 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
644 setTargetDAGCombine(ISD::FP_ROUND);
645 setTargetDAGCombine(ISD::STRICT_FP_ROUND);
646 setTargetDAGCombine(ISD::FP_EXTEND);
647 setTargetDAGCombine(ISD::SINT_TO_FP);
648 setTargetDAGCombine(ISD::UINT_TO_FP);
649 setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
650 setTargetDAGCombine(ISD::BSWAP);
651 setTargetDAGCombine(ISD::SDIV);
652 setTargetDAGCombine(ISD::UDIV);
653 setTargetDAGCombine(ISD::SREM);
654 setTargetDAGCombine(ISD::UREM);
655 setTargetDAGCombine(ISD::INTRINSIC_VOID);
656 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
657
658 // Handle intrinsics.
659 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
660 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
661
662 // We want to use MVC in preference to even a single load/store pair.
663 MaxStoresPerMemcpy = 0;
664 MaxStoresPerMemcpyOptSize = 0;
665
666 // The main memset sequence is a byte store followed by an MVC.
667 // Two STC or MV..I stores win over that, but the kind of fused stores
668 // generated by target-independent code don't when the byte value is
669 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
670 // than "STC;MVC". Handle the choice in target-specific code instead.
671 MaxStoresPerMemset = 0;
672 MaxStoresPerMemsetOptSize = 0;
673
674 // Default to having -disable-strictnode-mutation on
675 IsStrictFPEnabled = true;
676}
677
678bool SystemZTargetLowering::useSoftFloat() const {
679 return Subtarget.hasSoftFloat();
680}
681
682EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
683 LLVMContext &, EVT VT) const {
684 if (!VT.isVector())
685 return MVT::i32;
686 return VT.changeVectorElementTypeToInteger();
687}
688
689bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(
690 const MachineFunction &MF, EVT VT) const {
691 VT = VT.getScalarType();
692
693 if (!VT.isSimple())
694 return false;
695
696 switch (VT.getSimpleVT().SimpleTy) {
697 case MVT::f32:
698 case MVT::f64:
699 return true;
700 case MVT::f128:
701 return Subtarget.hasVectorEnhancements1();
702 default:
703 break;
704 }
705
706 return false;
707}
708
709// Return true if the constant can be generated with a vector instruction,
710// such as VGM, VGMB or VREPI.
711bool SystemZVectorConstantInfo::isVectorConstantLegal(
712 const SystemZSubtarget &Subtarget) {
713 const SystemZInstrInfo *TII =
714 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
715 if (!Subtarget.hasVector() ||
716 (isFP128 && !Subtarget.hasVectorEnhancements1()))
717 return false;
718
719 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
720 // preferred way of creating all-zero and all-one vectors so give it
721 // priority over other methods below.
722 unsigned Mask = 0;
723 unsigned I = 0;
724 for (; I < SystemZ::VectorBytes; ++I) {
725 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
726 if (Byte == 0xff)
727 Mask |= 1ULL << I;
728 else if (Byte != 0)
729 break;
730 }
731 if (I == SystemZ::VectorBytes) {
732 Opcode = SystemZISD::BYTE_MASK;
733 OpVals.push_back(Mask);
734 VecVT = MVT::getVectorVT(MVT::getIntegerVT(8), 16);
735 return true;
736 }
737
738 if (SplatBitSize > 64)
739 return false;
740
741 auto tryValue = [&](uint64_t Value) -> bool {
742 // Try VECTOR REPLICATE IMMEDIATE
743 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
744 if (isInt<16>(SignedValue)) {
745 OpVals.push_back(((unsigned) SignedValue));
746 Opcode = SystemZISD::REPLICATE;
747 VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
748 SystemZ::VectorBits / SplatBitSize);
749 return true;
750 }
751 // Try VECTOR GENERATE MASK
752 unsigned Start, End;
753 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
754 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
755 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
756 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
757 OpVals.push_back(Start - (64 - SplatBitSize));
758 OpVals.push_back(End - (64 - SplatBitSize));
759 Opcode = SystemZISD::ROTATE_MASK;
760 VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
761 SystemZ::VectorBits / SplatBitSize);
762 return true;
763 }
764 return false;
765 };
766
767 // First try assuming that any undefined bits above the highest set bit
768 // and below the lowest set bit are 1s. This increases the likelihood of
769 // being able to use a sign-extended element value in VECTOR REPLICATE
770 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
771 uint64_t SplatBitsZ = SplatBits.getZExtValue();
772 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
773 uint64_t Lower =
774 (SplatUndefZ & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
775 uint64_t Upper =
776 (SplatUndefZ & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
777 if (tryValue(SplatBitsZ | Upper | Lower))
778 return true;
779
780 // Now try assuming that any undefined bits between the first and
781 // last defined set bits are set. This increases the chances of
782 // using a non-wraparound mask.
783 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
784 return tryValue(SplatBitsZ | Middle);
785}
786
787SystemZVectorConstantInfo::SystemZVectorConstantInfo(APFloat FPImm) {
788 IntBits = FPImm.bitcastToAPInt().zextOrSelf(128);
789 isFP128 = (&FPImm.getSemantics() == &APFloat::IEEEquad());
790 SplatBits = FPImm.bitcastToAPInt();
791 unsigned Width = SplatBits.getBitWidth();
792 IntBits <<= (SystemZ::VectorBits - Width);
793
794 // Find the smallest splat.
795 while (Width > 8) {
796 unsigned HalfSize = Width / 2;
797 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
798 APInt LowValue = SplatBits.trunc(HalfSize);
799
800 // If the two halves do not match, stop here.
801 if (HighValue != LowValue || 8 > HalfSize)
802 break;
803
804 SplatBits = HighValue;
805 Width = HalfSize;
806 }
807 SplatUndef = 0;
808 SplatBitSize = Width;
809}
810
811SystemZVectorConstantInfo::SystemZVectorConstantInfo(BuildVectorSDNode *BVN) {
812 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
813 bool HasAnyUndefs;
814
815 // Get IntBits by finding the 128 bit splat.
816 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
817 true);
818
819 // Get SplatBits by finding the 8 bit or greater splat.
820 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
821 true);
822}
823
824bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
825 bool ForCodeSize) const {
826 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
827 if (Imm.isZero() || Imm.isNegZero())
828 return true;
829
830 return SystemZVectorConstantInfo(Imm).isVectorConstantLegal(Subtarget);
831}
832
833/// Returns true if stack probing through inline assembly is requested.
834bool SystemZTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
835 // If the function specifically requests inline stack probes, emit them.
836 if (MF.getFunction().hasFnAttribute("probe-stack"))
837 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
838 "inline-asm";
839 return false;
840}
841
842bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
843 // We can use CGFI or CLGFI.
844 return isInt<32>(Imm) || isUInt<32>(Imm);
845}
846
847bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
848 // We can use ALGFI or SLGFI.
849 return isUInt<32>(Imm) || isUInt<32>(-Imm);
850}
851
852bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(
853 EVT VT, unsigned, unsigned, MachineMemOperand::Flags, bool *Fast) const {
854 // Unaligned accesses should never be slower than the expanded version.
855 // We check specifically for aligned accesses in the few cases where
856 // they are required.
857 if (Fast)
858 *Fast = true;
859 return true;
860}
861
862// Information about the addressing mode for a memory access.
863struct AddressingMode {
864 // True if a long displacement is supported.
865 bool LongDisplacement;
866
867 // True if use of index register is supported.
868 bool IndexReg;
869
870 AddressingMode(bool LongDispl, bool IdxReg) :
871 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
872};
873
874// Return the desired addressing mode for a Load which has only one use (in
875// the same block) which is a Store.
876static AddressingMode getLoadStoreAddrMode(bool HasVector,
877 Type *Ty) {
878 // With vector support a Load->Store combination may be combined to either
879 // an MVC or vector operations and it seems to work best to allow the
880 // vector addressing mode.
881 if (HasVector)
882 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
883
884 // Otherwise only the MVC case is special.
885 bool MVC = Ty->isIntegerTy(8);
886 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
887}
888
889// Return the addressing mode which seems most desirable given an LLVM
890// Instruction pointer.
891static AddressingMode
892supportedAddressingMode(Instruction *I, bool HasVector) {
893 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
894 switch (II->getIntrinsicID()) {
895 default: break;
896 case Intrinsic::memset:
897 case Intrinsic::memmove:
898 case Intrinsic::memcpy:
899 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
900 }
901 }
902
903 if (isa<LoadInst>(I) && I->hasOneUse()) {
904 auto *SingleUser = cast<Instruction>(*I->user_begin());
905 if (SingleUser->getParent() == I->getParent()) {
906 if (isa<ICmpInst>(SingleUser)) {
907 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
908 if (C->getBitWidth() <= 64 &&
909 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
910 // Comparison of memory with 16 bit signed / unsigned immediate
911 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
912 } else if (isa<StoreInst>(SingleUser))
913 // Load->Store
914 return getLoadStoreAddrMode(HasVector, I->getType());
915 }
916 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
917 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
918 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
919 // Load->Store
920 return getLoadStoreAddrMode(HasVector, LoadI->getType());
921 }
922
923 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
924
925 // * Use LDE instead of LE/LEY for z13 to avoid partial register
926 // dependencies (LDE only supports small offsets).
927 // * Utilize the vector registers to hold floating point
928 // values (vector load / store instructions only support small
929 // offsets).
930
931 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
932 I->getOperand(0)->getType());
933 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
934 bool IsVectorAccess = MemAccessTy->isVectorTy();
935
936 // A store of an extracted vector element will be combined into a VSTE type
937 // instruction.
938 if (!IsVectorAccess && isa<StoreInst>(I)) {
939 Value *DataOp = I->getOperand(0);
940 if (isa<ExtractElementInst>(DataOp))
941 IsVectorAccess = true;
942 }
943
944 // A load which gets inserted into a vector element will be combined into a
945 // VLE type instruction.
946 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
947 User *LoadUser = *I->user_begin();
948 if (isa<InsertElementInst>(LoadUser))
949 IsVectorAccess = true;
950 }
951
952 if (IsFPAccess || IsVectorAccess)
953 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
954 }
955
956 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
957}
958
959bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
960 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
961 // Punt on globals for now, although they can be used in limited
962 // RELATIVE LONG cases.
963 if (AM.BaseGV)
964 return false;
965
966 // Require a 20-bit signed offset.
967 if (!isInt<20>(AM.BaseOffs))
968 return false;
969
970 AddressingMode SupportedAM(true, true);
971 if (I != nullptr)
972 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
973
974 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
975 return false;
976
977 if (!SupportedAM.IndexReg)
978 // No indexing allowed.
979 return AM.Scale == 0;
980 else
981 // Indexing is OK but no scale factor can be applied.
982 return AM.Scale == 0 || AM.Scale == 1;
983}
984
985bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
986 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
987 return false;
988 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedSize();
989 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedSize();
990 return FromBits > ToBits;
991}
992
993bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
994 if (!FromVT.isInteger() || !ToVT.isInteger())
995 return false;
996 unsigned FromBits = FromVT.getFixedSizeInBits();
997 unsigned ToBits = ToVT.getFixedSizeInBits();
998 return FromBits > ToBits;
999}
1000
1001//===----------------------------------------------------------------------===//
1002// Inline asm support
1003//===----------------------------------------------------------------------===//
1004
1005TargetLowering::ConstraintType
1006SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
1007 if (Constraint.size() == 1) {
1008 switch (Constraint[0]) {
1009 case 'a': // Address register
1010 case 'd': // Data register (equivalent to 'r')
1011 case 'f': // Floating-point register
1012 case 'h': // High-part register
1013 case 'r': // General-purpose register
1014 case 'v': // Vector register
1015 return C_RegisterClass;
1016
1017 case 'Q': // Memory with base and unsigned 12-bit displacement
1018 case 'R': // Likewise, plus an index
1019 case 'S': // Memory with base and signed 20-bit displacement
1020 case 'T': // Likewise, plus an index
1021 case 'm': // Equivalent to 'T'.
1022 return C_Memory;
1023
1024 case 'I': // Unsigned 8-bit constant
1025 case 'J': // Unsigned 12-bit constant
1026 case 'K': // Signed 16-bit constant
1027 case 'L': // Signed 20-bit displacement (on all targets we support)
1028 case 'M': // 0x7fffffff
1029 return C_Immediate;
1030
1031 default:
1032 break;
1033 }
1034 }
1035 return TargetLowering::getConstraintType(Constraint);
1036}
1037
1038TargetLowering::ConstraintWeight SystemZTargetLowering::
1039getSingleConstraintMatchWeight(AsmOperandInfo &info,
1040 const char *constraint) const {
1041 ConstraintWeight weight = CW_Invalid;
1042 Value *CallOperandVal = info.CallOperandVal;
1043 // If we don't have a value, we can't do a match,
1044 // but allow it at the lowest weight.
1045 if (!CallOperandVal)
1046 return CW_Default;
1047 Type *type = CallOperandVal->getType();
1048 // Look at the constraint type.
1049 switch (*constraint) {
1050 default:
1051 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1052 break;
1053
1054 case 'a': // Address register
1055 case 'd': // Data register (equivalent to 'r')
1056 case 'h': // High-part register
1057 case 'r': // General-purpose register
1058 if (CallOperandVal->getType()->isIntegerTy())
1059 weight = CW_Register;
1060 break;
1061
1062 case 'f': // Floating-point register
1063 if (type->isFloatingPointTy())
1064 weight = CW_Register;
1065 break;
1066
1067 case 'v': // Vector register
1068 if ((type->isVectorTy() || type->isFloatingPointTy()) &&
1069 Subtarget.hasVector())
1070 weight = CW_Register;
1071 break;
1072
1073 case 'I': // Unsigned 8-bit constant
1074 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1075 if (isUInt<8>(C->getZExtValue()))
1076 weight = CW_Constant;
1077 break;
1078
1079 case 'J': // Unsigned 12-bit constant
1080 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1081 if (isUInt<12>(C->getZExtValue()))
1082 weight = CW_Constant;
1083 break;
1084
1085 case 'K': // Signed 16-bit constant
1086 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1087 if (isInt<16>(C->getSExtValue()))
1088 weight = CW_Constant;
1089 break;
1090
1091 case 'L': // Signed 20-bit displacement (on all targets we support)
1092 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1093 if (isInt<20>(C->getSExtValue()))
1094 weight = CW_Constant;
1095 break;
1096
1097 case 'M': // 0x7fffffff
1098 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1099 if (C->getZExtValue() == 0x7fffffff)
1100 weight = CW_Constant;
1101 break;
1102 }
1103 return weight;
1104}
1105
1106// Parse a "{tNNN}" register constraint for which the register type "t"
1107// has already been verified. MC is the class associated with "t" and
1108// Map maps 0-based register numbers to LLVM register numbers.
1109static std::pair<unsigned, const TargetRegisterClass *>
1110parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
1111 const unsigned *Map, unsigned Size) {
1112 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1113 if (isdigit(Constraint[2])) {
1114 unsigned Index;
1115 bool Failed =
1116 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1117 if (!Failed && Index < Size && Map[Index])
1118 return std::make_pair(Map[Index], RC);
1119 }
1120 return std::make_pair(0U, nullptr);
1121}
1122
1123std::pair<unsigned, const TargetRegisterClass *>
1124SystemZTargetLowering::getRegForInlineAsmConstraint(
1125 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1126 if (Constraint.size() == 1) {
1127 // GCC Constraint Letters
1128 switch (Constraint[0]) {
1129 default: break;
1130 case 'd': // Data register (equivalent to 'r')
1131 case 'r': // General-purpose register
1132 if (VT == MVT::i64)
1133 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1134 else if (VT == MVT::i128)
1135 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1136 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1137
1138 case 'a': // Address register
1139 if (VT == MVT::i64)
1140 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1141 else if (VT == MVT::i128)
1142 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1143 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1144
1145 case 'h': // High-part register (an LLVM extension)
1146 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1147
1148 case 'f': // Floating-point register
1149 if (!useSoftFloat()) {
1150 if (VT == MVT::f64)
1151 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1152 else if (VT == MVT::f128)
1153 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1154 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1155 }
1156 break;
1157 case 'v': // Vector register
1158 if (Subtarget.hasVector()) {
1159 if (VT == MVT::f32)
1160 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1161 if (VT == MVT::f64)
1162 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1163 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1164 }
1165 break;
1166 }
1167 }
1168 if (Constraint.size() > 0 && Constraint[0] == '{') {
1169 // We need to override the default register parsing for GPRs and FPRs
1170 // because the interpretation depends on VT. The internal names of
1171 // the registers are also different from the external names
1172 // (F0D and F0S instead of F0, etc.).
1173 if (Constraint[1] == 'r') {
1174 if (VT == MVT::i32)
1175 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1176 SystemZMC::GR32Regs, 16);
1177 if (VT == MVT::i128)
1178 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1179 SystemZMC::GR128Regs, 16);
1180 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1181 SystemZMC::GR64Regs, 16);
1182 }
1183 if (Constraint[1] == 'f') {
1184 if (useSoftFloat())
1185 return std::make_pair(
1186 0u, static_cast<const TargetRegisterClass *>(nullptr));
1187 if (VT == MVT::f32)
1188 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1189 SystemZMC::FP32Regs, 16);
1190 if (VT == MVT::f128)
1191 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1192 SystemZMC::FP128Regs, 16);
1193 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1194 SystemZMC::FP64Regs, 16);
1195 }
1196 if (Constraint[1] == 'v') {
1197 if (!Subtarget.hasVector())
1198 return std::make_pair(
1199 0u, static_cast<const TargetRegisterClass *>(nullptr));
1200 if (VT == MVT::f32)
1201 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1202 SystemZMC::VR32Regs, 32);
1203 if (VT == MVT::f64)
1204 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1205 SystemZMC::VR64Regs, 32);
1206 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1207 SystemZMC::VR128Regs, 32);
1208 }
1209 }
1210 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1211}
1212
1213// FIXME? Maybe this could be a TableGen attribute on some registers and
1214// this table could be generated automatically from RegInfo.
1215Register SystemZTargetLowering::getRegisterByName(const char *RegName, LLT VT,
1216 const MachineFunction &MF) const {
1217
1218 Register Reg = StringSwitch<Register>(RegName)
1219 .Case("r15", SystemZ::R15D)
1220 .Default(0);
1221 if (Reg)
1222 return Reg;
1223 report_fatal_error("Invalid register name global variable");
1224}
1225
1226void SystemZTargetLowering::
1227LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1228 std::vector<SDValue> &Ops,
1229 SelectionDAG &DAG) const {
1230 // Only support length 1 constraints for now.
1231 if (Constraint.length() == 1) {
1232 switch (Constraint[0]) {
1233 case 'I': // Unsigned 8-bit constant
1234 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1235 if (isUInt<8>(C->getZExtValue()))
1236 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1237 Op.getValueType()));
1238 return;
1239
1240 case 'J': // Unsigned 12-bit constant
1241 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1242 if (isUInt<12>(C->getZExtValue()))
1243 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1244 Op.getValueType()));
1245 return;
1246
1247 case 'K': // Signed 16-bit constant
1248 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1249 if (isInt<16>(C->getSExtValue()))
1250 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1251 Op.getValueType()));
1252 return;
1253
1254 case 'L': // Signed 20-bit displacement (on all targets we support)
1255 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1256 if (isInt<20>(C->getSExtValue()))
1257 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1258 Op.getValueType()));
1259 return;
1260
1261 case 'M': // 0x7fffffff
1262 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1263 if (C->getZExtValue() == 0x7fffffff)
1264 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1265 Op.getValueType()));
1266 return;
1267 }
1268 }
1269 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1270}
1271
1272//===----------------------------------------------------------------------===//
1273// Calling conventions
1274//===----------------------------------------------------------------------===//
1275
1276#include "SystemZGenCallingConv.inc"
1277
1278const MCPhysReg *SystemZTargetLowering::getScratchRegisters(
1279 CallingConv::ID) const {
1280 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1281 SystemZ::R14D, 0 };
1282 return ScratchRegs;
1283}
1284
1285bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
1286 Type *ToType) const {
1287 return isTruncateFree(FromType, ToType);
1288}
1289
1290bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
1291 return CI->isTailCall();
1292}
1293
1294// We do not yet support 128-bit single-element vector types. If the user
1295// attempts to use such types as function argument or return type, prefer
1296// to error out instead of emitting code violating the ABI.
1297static void VerifyVectorType(MVT VT, EVT ArgVT) {
1298 if (ArgVT.isVector() && !VT.isVector())
1299 report_fatal_error("Unsupported vector argument or return type");
1300}
1301
1302static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
1303 for (unsigned i = 0; i < Ins.size(); ++i)
1304 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
1305}
1306
1307static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1308 for (unsigned i = 0; i < Outs.size(); ++i)
1309 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
1310}
1311
1312// Value is a value that has been passed to us in the location described by VA
1313// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1314// any loads onto Chain.
1315static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
1316 CCValAssign &VA, SDValue Chain,
1317 SDValue Value) {
1318 // If the argument has been promoted from a smaller type, insert an
1319 // assertion to capture this.
1320 if (VA.getLocInfo() == CCValAssign::SExt)
1321 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
1322 DAG.getValueType(VA.getValVT()));
1323 else if (VA.getLocInfo() == CCValAssign::ZExt)
1324 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
1325 DAG.getValueType(VA.getValVT()));
1326
1327 if (VA.isExtInLoc())
1328 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1329 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1330 // If this is a short vector argument loaded from the stack,
1331 // extend from i64 to full vector size and then bitcast.
1332 assert(VA.getLocVT() == MVT::i64);
1333 assert(VA.getValVT().isVector());
1334 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1335 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1336 } else
1337 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1338 return Value;
1339}
1340
1341// Value is a value of type VA.getValVT() that we need to copy into
1342// the location described by VA. Return a copy of Value converted to
1343// VA.getValVT(). The caller is responsible for handling indirect values.
1344static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
1345 CCValAssign &VA, SDValue Value) {
1346 switch (VA.getLocInfo()) {
1347 case CCValAssign::SExt:
1348 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1349 case CCValAssign::ZExt:
1350 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1351 case CCValAssign::AExt:
1352 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1353 case CCValAssign::BCvt:
1354 // If this is a short vector argument to be stored to the stack,
1355 // bitcast to v2i64 and then extract first element.
1356 assert(VA.getLocVT() == MVT::i64);
1357 assert(VA.getValVT().isVector());
1358 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
1359 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1360 DAG.getConstant(0, DL, MVT::i32));
1361 case CCValAssign::Full:
1362 return Value;
1363 default:
1364 llvm_unreachable("Unhandled getLocInfo()");
1365 }
1366}
1367
1368SDValue SystemZTargetLowering::LowerFormalArguments(
1369 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1370 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1371 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1372 MachineFunction &MF = DAG.getMachineFunction();
1373 MachineFrameInfo &MFI = MF.getFrameInfo();
1374 MachineRegisterInfo &MRI = MF.getRegInfo();
1375 SystemZMachineFunctionInfo *FuncInfo =
1376 MF.getInfo<SystemZMachineFunctionInfo>();
1377 auto *TFL =
1378 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
1379 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1380
1381 // Detect unsupported vector argument types.
1382 if (Subtarget.hasVector())
1383 VerifyVectorTypes(Ins);
1384
1385 // Assign locations to all of the incoming arguments.
1386 SmallVector<CCValAssign, 16> ArgLocs;
1387 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1388 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
1389
1390 unsigned NumFixedGPRs = 0;
1391 unsigned NumFixedFPRs = 0;
1392 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1393 SDValue ArgValue;
1394 CCValAssign &VA = ArgLocs[I];
1395 EVT LocVT = VA.getLocVT();
1396 if (VA.isRegLoc()) {
1397 // Arguments passed in registers
1398 const TargetRegisterClass *RC;
1399 switch (LocVT.getSimpleVT().SimpleTy) {
1400 default:
1401 // Integers smaller than i64 should be promoted to i64.
1402 llvm_unreachable("Unexpected argument type");
1403 case MVT::i32:
1404 NumFixedGPRs += 1;
1405 RC = &SystemZ::GR32BitRegClass;
1406 break;
1407 case MVT::i64:
1408 NumFixedGPRs += 1;
1409 RC = &SystemZ::GR64BitRegClass;
1410 break;
1411 case MVT::f32:
1412 NumFixedFPRs += 1;
1413 RC = &SystemZ::FP32BitRegClass;
1414 break;
1415 case MVT::f64:
1416 NumFixedFPRs += 1;
1417 RC = &SystemZ::FP64BitRegClass;
1418 break;
1419 case MVT::v16i8:
1420 case MVT::v8i16:
1421 case MVT::v4i32:
1422 case MVT::v2i64:
1423 case MVT::v4f32:
1424 case MVT::v2f64:
1425 RC = &SystemZ::VR128BitRegClass;
1426 break;
1427 }
1428
1429 Register VReg = MRI.createVirtualRegister(RC);
1430 MRI.addLiveIn(VA.getLocReg(), VReg);
1431 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1432 } else {
1433 assert(VA.isMemLoc() && "Argument not register or memory");
1434
1435 // Create the frame index object for this incoming parameter.
1436 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1437 VA.getLocMemOffset(), true);
1438
1439 // Create the SelectionDAG nodes corresponding to a load
1440 // from this parameter. Unpromoted ints and floats are
1441 // passed as right-justified 8-byte values.
1442 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1443 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1444 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1445 DAG.getIntPtrConstant(4, DL));
1446 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1447 MachinePointerInfo::getFixedStack(MF, FI));
1448 }
1449
1450 // Convert the value of the argument register into the value that's
1451 // being passed.
1452 if (VA.getLocInfo() == CCValAssign::Indirect) {
1453 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1454 MachinePointerInfo()));
1455 // If the original argument was split (e.g. i128), we need
1456 // to load all parts of it here (using the same address).
1457 unsigned ArgIndex = Ins[I].OrigArgIndex;
1458 assert (Ins[I].PartOffset == 0);
1459 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1460 CCValAssign &PartVA = ArgLocs[I + 1];
1461 unsigned PartOffset = Ins[I + 1].PartOffset;
1462 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1463 DAG.getIntPtrConstant(PartOffset, DL));
1464 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1465 MachinePointerInfo()));
1466 ++I;
1467 }
1468 } else
1469 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1470 }
1471
1472 if (IsVarArg) {
1473 // Save the number of non-varargs registers for later use by va_start, etc.
1474 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1475 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1476
1477 // Likewise the address (in the form of a frame index) of where the
1478 // first stack vararg would be. The 1-byte size here is arbitrary.
1479 int64_t StackSize = CCInfo.getNextStackOffset();
1480 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1481
1482 // ...and a similar frame index for the caller-allocated save area
1483 // that will be used to store the incoming registers.
1484 int64_t RegSaveOffset =
1485 -SystemZMC::CallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
1486 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1487 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1488
1489 // Store the FPR varargs in the reserved frame slots. (We store the
1490 // GPRs as part of the prologue.)
1491 if (NumFixedFPRs < SystemZ::NumArgFPRs && !useSoftFloat()) {
1492 SDValue MemOps[SystemZ::NumArgFPRs];
1493 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1494 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ArgFPRs[I]);
1495 int FI =
1496 MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize + Offset, true);
1497 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1498 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1499 &SystemZ::FP64BitRegClass);
1500 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1501 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1502 MachinePointerInfo::getFixedStack(MF, FI));
1503 }
1504 // Join the stores, which are independent of one another.
1505 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1506 makeArrayRef(&MemOps[NumFixedFPRs],
1507 SystemZ::NumArgFPRs-NumFixedFPRs));
1508 }
1509 }
1510
1511 return Chain;
1512}
1513
1514static bool canUseSiblingCall(const CCState &ArgCCInfo,
1515 SmallVectorImpl<CCValAssign> &ArgLocs,
1516 SmallVectorImpl<ISD::OutputArg> &Outs) {
1517 // Punt if there are any indirect or stack arguments, or if the call
1518 // needs the callee-saved argument register R6, or if the call uses
1519 // the callee-saved register arguments SwiftSelf and SwiftError.
1520 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1521 CCValAssign &VA = ArgLocs[I];
1522 if (VA.getLocInfo() == CCValAssign::Indirect)
1523 return false;
1524 if (!VA.isRegLoc())
1525 return false;
1526 Register Reg = VA.getLocReg();
1527 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1528 return false;
1529 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1530 return false;
1531 }
1532 return true;
1533}
1534
1535SDValue
1536SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1537 SmallVectorImpl<SDValue> &InVals) const {
1538 SelectionDAG &DAG = CLI.DAG;
1539 SDLoc &DL = CLI.DL;
1540 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1541 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1542 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1543 SDValue Chain = CLI.Chain;
1544 SDValue Callee = CLI.Callee;
1545 bool &IsTailCall = CLI.IsTailCall;
1546 CallingConv::ID CallConv = CLI.CallConv;
1547 bool IsVarArg = CLI.IsVarArg;
1548 MachineFunction &MF = DAG.getMachineFunction();
1549 EVT PtrVT = getPointerTy(MF.getDataLayout());
1550
1551 // Detect unsupported vector argument and return types.
1552 if (Subtarget.hasVector()) {
1553 VerifyVectorTypes(Outs);
1554 VerifyVectorTypes(Ins);
1555 }
1556
1557 // Analyze the operands of the call, assigning locations to each operand.
1558 SmallVector<CCValAssign, 16> ArgLocs;
1559 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1560 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1561
1562 // We don't support GuaranteedTailCallOpt, only automatically-detected
1563 // sibling calls.
1564 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1565 IsTailCall = false;
1566
1567 // Get a count of how many bytes are to be pushed on the stack.
1568 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1569
1570 // Mark the start of the call.
1571 if (!IsTailCall)
1572 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1573
1574 // Copy argument values to their designated locations.
1575 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1576 SmallVector<SDValue, 8> MemOpChains;
1577 SDValue StackPtr;
1578 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1579 CCValAssign &VA = ArgLocs[I];
1580 SDValue ArgValue = OutVals[I];
1581
1582 if (VA.getLocInfo() == CCValAssign::Indirect) {
1583 // Store the argument in a stack slot and pass its address.
1584 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1585 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1586 MemOpChains.push_back(
1587 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1588 MachinePointerInfo::getFixedStack(MF, FI)));
1589 // If the original argument was split (e.g. i128), we need
1590 // to store all parts of it here (and pass just one address).
1591 unsigned ArgIndex = Outs[I].OrigArgIndex;
1592 assert (Outs[I].PartOffset == 0);
1593 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1594 SDValue PartValue = OutVals[I + 1];
1595 unsigned PartOffset = Outs[I + 1].PartOffset;
1596 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1597 DAG.getIntPtrConstant(PartOffset, DL));
1598 MemOpChains.push_back(
1599 DAG.getStore(Chain, DL, PartValue, Address,
1600 MachinePointerInfo::getFixedStack(MF, FI)));
1601 ++I;
1602 }
1603 ArgValue = SpillSlot;
1604 } else
1605 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1606
1607 if (VA.isRegLoc())
1608 // Queue up the argument copies and emit them at the end.
1609 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1610 else {
1611 assert(VA.isMemLoc() && "Argument not register or memory");
1612
1613 // Work out the address of the stack slot. Unpromoted ints and
1614 // floats are passed as right-justified 8-byte values.
1615 if (!StackPtr.getNode())
1616 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1617 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1618 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1619 Offset += 4;
1620 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1621 DAG.getIntPtrConstant(Offset, DL));
1622
1623 // Emit the store.
1624 MemOpChains.push_back(
1625 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1626 }
1627 }
1628
1629 // Join the stores, which are independent of one another.
1630 if (!MemOpChains.empty())
1631 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1632
1633 // Accept direct calls by converting symbolic call addresses to the
1634 // associated Target* opcodes. Force %r1 to be used for indirect
1635 // tail calls.
1636 SDValue Glue;
1637 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1638 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1639 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1640 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1641 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1642 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1643 } else if (IsTailCall) {
1644 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1645 Glue = Chain.getValue(1);
1646 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1647 }
1648
1649 // Build a sequence of copy-to-reg nodes, chained and glued together.
1650 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1651 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1652 RegsToPass[I].second, Glue);
1653 Glue = Chain.getValue(1);
1654 }
1655
1656 // The first call operand is the chain and the second is the target address.
1657 SmallVector<SDValue, 8> Ops;
1658 Ops.push_back(Chain);
1659 Ops.push_back(Callee);
1660
1661 // Add argument registers to the end of the list so that they are
1662 // known live into the call.
1663 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1664 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1665 RegsToPass[I].second.getValueType()));
1666
1667 // Add a register mask operand representing the call-preserved registers.
1668 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1669 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1670 assert(Mask && "Missing call preserved mask for calling convention");
1671 Ops.push_back(DAG.getRegisterMask(Mask));
1672
1673 // Glue the call to the argument copies, if any.
1674 if (Glue.getNode())
1675 Ops.push_back(Glue);
1676
1677 // Emit the call.
1678 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1679 if (IsTailCall)
1680 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1681 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1682 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
1683 Glue = Chain.getValue(1);
1684
1685 // Mark the end of the call, which is glued to the call itself.
1686 Chain = DAG.getCALLSEQ_END(Chain,
1687 DAG.getConstant(NumBytes, DL, PtrVT, true),
1688 DAG.getConstant(0, DL, PtrVT, true),
1689 Glue, DL);
1690 Glue = Chain.getValue(1);
1691
1692 // Assign locations to each value returned by this call.
1693 SmallVector<CCValAssign, 16> RetLocs;
1694 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1695 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1696
1697 // Copy all of the result registers out of their specified physreg.
1698 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1699 CCValAssign &VA = RetLocs[I];
1700
1701 // Copy the value out, gluing the copy to the end of the call sequence.
1702 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1703 VA.getLocVT(), Glue);
1704 Chain = RetValue.getValue(1);
1705 Glue = RetValue.getValue(2);
1706
1707 // Convert the value of the return register into the value that's
1708 // being returned.
1709 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1710 }
1711
1712 return Chain;
1713}
1714
1715bool SystemZTargetLowering::
1716CanLowerReturn(CallingConv::ID CallConv,
1717 MachineFunction &MF, bool isVarArg,
1718 const SmallVectorImpl<ISD::OutputArg> &Outs,
1719 LLVMContext &Context) const {
1720 // Detect unsupported vector return types.
1721 if (Subtarget.hasVector())
1722 VerifyVectorTypes(Outs);
1723
1724 // Special case that we cannot easily detect in RetCC_SystemZ since
1725 // i128 is not a legal type.
1726 for (auto &Out : Outs)
1727 if (Out.ArgVT == MVT::i128)
1728 return false;
1729
1730 SmallVector<CCValAssign, 16> RetLocs;
1731 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1732 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1733}
1734
1735SDValue
1736SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1737 bool IsVarArg,
1738 const SmallVectorImpl<ISD::OutputArg> &Outs,
1739 const SmallVectorImpl<SDValue> &OutVals,
1740 const SDLoc &DL, SelectionDAG &DAG) const {
1741 MachineFunction &MF = DAG.getMachineFunction();
1742
1743 // Detect unsupported vector return types.
1744 if (Subtarget.hasVector())
1745 VerifyVectorTypes(Outs);
1746
1747 // Assign locations to each returned value.
1748 SmallVector<CCValAssign, 16> RetLocs;
1749 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1750 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1751
1752 // Quick exit for void returns
1753 if (RetLocs.empty())
1754 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1755
1756 if (CallConv == CallingConv::GHC)
1757 report_fatal_error("GHC functions return void only");
1758
1759 // Copy the result values into the output registers.
1760 SDValue Glue;
1761 SmallVector<SDValue, 4> RetOps;
1762 RetOps.push_back(Chain);
1763 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1764 CCValAssign &VA = RetLocs[I];
1765 SDValue RetValue = OutVals[I];
1766
1767 // Make the return register live on exit.
1768 assert(VA.isRegLoc() && "Can only return in registers!");
1769
1770 // Promote the value as required.
1771 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1772
1773 // Chain and glue the copies together.
1774 Register Reg = VA.getLocReg();
1775 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1776 Glue = Chain.getValue(1);
1777 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1778 }
1779
1780 // Update chain and glue.
1781 RetOps[0] = Chain;
1782 if (Glue.getNode())
1783 RetOps.push_back(Glue);
1784
1785 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1786}
1787
1788// Return true if Op is an intrinsic node with chain that returns the CC value
1789// as its only (other) argument. Provide the associated SystemZISD opcode and
1790// the mask of valid CC values if so.
1791static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1792 unsigned &CCValid) {
1793 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1794 switch (Id) {
1795 case Intrinsic::s390_tbegin:
1796 Opcode = SystemZISD::TBEGIN;
1797 CCValid = SystemZ::CCMASK_TBEGIN;
1798 return true;
1799
1800 case Intrinsic::s390_tbegin_nofloat:
1801 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1802 CCValid = SystemZ::CCMASK_TBEGIN;
1803 return true;
1804
1805 case Intrinsic::s390_tend:
1806 Opcode = SystemZISD::TEND;
1807 CCValid = SystemZ::CCMASK_TEND;
1808 return true;
1809
1810 default:
1811 return false;
1812 }
1813}
1814
1815// Return true if Op is an intrinsic node without chain that returns the
1816// CC value as its final argument. Provide the associated SystemZISD
1817// opcode and the mask of valid CC values if so.
1818static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1819 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1820 switch (Id) {
1821 case Intrinsic::s390_vpkshs:
1822 case Intrinsic::s390_vpksfs:
1823 case Intrinsic::s390_vpksgs:
1824 Opcode = SystemZISD::PACKS_CC;
1825 CCValid = SystemZ::CCMASK_VCMP;
1826 return true;
1827
1828 case Intrinsic::s390_vpklshs:
1829 case Intrinsic::s390_vpklsfs:
1830 case Intrinsic::s390_vpklsgs:
1831 Opcode = SystemZISD::PACKLS_CC;
1832 CCValid = SystemZ::CCMASK_VCMP;
1833 return true;
1834
1835 case Intrinsic::s390_vceqbs:
1836 case Intrinsic::s390_vceqhs:
1837 case Intrinsic::s390_vceqfs:
1838 case Intrinsic::s390_vceqgs:
1839 Opcode = SystemZISD::VICMPES;
1840 CCValid = SystemZ::CCMASK_VCMP;
1841 return true;
1842
1843 case Intrinsic::s390_vchbs:
1844 case Intrinsic::s390_vchhs:
1845 case Intrinsic::s390_vchfs:
1846 case Intrinsic::s390_vchgs:
1847 Opcode = SystemZISD::VICMPHS;
1848 CCValid = SystemZ::CCMASK_VCMP;
1849 return true;
1850
1851 case Intrinsic::s390_vchlbs:
1852 case Intrinsic::s390_vchlhs:
1853 case Intrinsic::s390_vchlfs:
1854 case Intrinsic::s390_vchlgs:
1855 Opcode = SystemZISD::VICMPHLS;
1856 CCValid = SystemZ::CCMASK_VCMP;
1857 return true;
1858
1859 case Intrinsic::s390_vtm:
1860 Opcode = SystemZISD::VTM;
1861 CCValid = SystemZ::CCMASK_VCMP;
1862 return true;
1863
1864 case Intrinsic::s390_vfaebs:
1865 case Intrinsic::s390_vfaehs:
1866 case Intrinsic::s390_vfaefs:
1867 Opcode = SystemZISD::VFAE_CC;
1868 CCValid = SystemZ::CCMASK_ANY;
1869 return true;
1870
1871 case Intrinsic::s390_vfaezbs:
1872 case Intrinsic::s390_vfaezhs:
1873 case Intrinsic::s390_vfaezfs:
1874 Opcode = SystemZISD::VFAEZ_CC;
1875 CCValid = SystemZ::CCMASK_ANY;
1876 return true;
1877
1878 case Intrinsic::s390_vfeebs:
1879 case Intrinsic::s390_vfeehs:
1880 case Intrinsic::s390_vfeefs:
1881 Opcode = SystemZISD::VFEE_CC;
1882 CCValid = SystemZ::CCMASK_ANY;
1883 return true;
1884
1885 case Intrinsic::s390_vfeezbs:
1886 case Intrinsic::s390_vfeezhs:
1887 case Intrinsic::s390_vfeezfs:
1888 Opcode = SystemZISD::VFEEZ_CC;
1889 CCValid = SystemZ::CCMASK_ANY;
1890 return true;
1891
1892 case Intrinsic::s390_vfenebs:
1893 case Intrinsic::s390_vfenehs:
1894 case Intrinsic::s390_vfenefs:
1895 Opcode = SystemZISD::VFENE_CC;
1896 CCValid = SystemZ::CCMASK_ANY;
1897 return true;
1898
1899 case Intrinsic::s390_vfenezbs:
1900 case Intrinsic::s390_vfenezhs:
1901 case Intrinsic::s390_vfenezfs:
1902 Opcode = SystemZISD::VFENEZ_CC;
1903 CCValid = SystemZ::CCMASK_ANY;
1904 return true;
1905
1906 case Intrinsic::s390_vistrbs:
1907 case Intrinsic::s390_vistrhs:
1908 case Intrinsic::s390_vistrfs:
1909 Opcode = SystemZISD::VISTR_CC;
1910 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1911 return true;
1912
1913 case Intrinsic::s390_vstrcbs:
1914 case Intrinsic::s390_vstrchs:
1915 case Intrinsic::s390_vstrcfs:
1916 Opcode = SystemZISD::VSTRC_CC;
1917 CCValid = SystemZ::CCMASK_ANY;
1918 return true;
1919
1920 case Intrinsic::s390_vstrczbs:
1921 case Intrinsic::s390_vstrczhs:
1922 case Intrinsic::s390_vstrczfs:
1923 Opcode = SystemZISD::VSTRCZ_CC;
1924 CCValid = SystemZ::CCMASK_ANY;
1925 return true;
1926
1927 case Intrinsic::s390_vstrsb:
1928 case Intrinsic::s390_vstrsh:
1929 case Intrinsic::s390_vstrsf:
1930 Opcode = SystemZISD::VSTRS_CC;
1931 CCValid = SystemZ::CCMASK_ANY;
1932 return true;
1933
1934 case Intrinsic::s390_vstrszb:
1935 case Intrinsic::s390_vstrszh:
1936 case Intrinsic::s390_vstrszf:
1937 Opcode = SystemZISD::VSTRSZ_CC;
1938 CCValid = SystemZ::CCMASK_ANY;
1939 return true;
1940
1941 case Intrinsic::s390_vfcedbs:
1942 case Intrinsic::s390_vfcesbs:
1943 Opcode = SystemZISD::VFCMPES;
1944 CCValid = SystemZ::CCMASK_VCMP;
1945 return true;
1946
1947 case Intrinsic::s390_vfchdbs:
1948 case Intrinsic::s390_vfchsbs:
1949 Opcode = SystemZISD::VFCMPHS;
1950 CCValid = SystemZ::CCMASK_VCMP;
1951 return true;
1952
1953 case Intrinsic::s390_vfchedbs:
1954 case Intrinsic::s390_vfchesbs:
1955 Opcode = SystemZISD::VFCMPHES;
1956 CCValid = SystemZ::CCMASK_VCMP;
1957 return true;
1958
1959 case Intrinsic::s390_vftcidb:
1960 case Intrinsic::s390_vftcisb:
1961 Opcode = SystemZISD::VFTCI;
1962 CCValid = SystemZ::CCMASK_VCMP;
1963 return true;
1964
1965 case Intrinsic::s390_tdc:
1966 Opcode = SystemZISD::TDC;
1967 CCValid = SystemZ::CCMASK_TDC;
1968 return true;
1969
1970 default:
1971 return false;
1972 }
1973}
1974
1975// Emit an intrinsic with chain and an explicit CC register result.
1976static SDNode *emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op,
1977 unsigned Opcode) {
1978 // Copy all operands except the intrinsic ID.
1979 unsigned NumOps = Op.getNumOperands();
1980 SmallVector<SDValue, 6> Ops;
1981 Ops.reserve(NumOps - 1);
1982 Ops.push_back(Op.getOperand(0));
1983 for (unsigned I = 2; I < NumOps; ++I)
1984 Ops.push_back(Op.getOperand(I));
1985
1986 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1987 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
1988 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1989 SDValue OldChain = SDValue(Op.getNode(), 1);
1990 SDValue NewChain = SDValue(Intr.getNode(), 1);
1991 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1992 return Intr.getNode();
1993}
1994
1995// Emit an intrinsic with an explicit CC register result.
1996static SDNode *emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op,
1997 unsigned Opcode) {
1998 // Copy all operands except the intrinsic ID.
1999 unsigned NumOps = Op.getNumOperands();
2000 SmallVector<SDValue, 6> Ops;
2001 Ops.reserve(NumOps - 1);
2002 for (unsigned I = 1; I < NumOps; ++I)
2003 Ops.push_back(Op.getOperand(I));
2004
2005 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops);
2006 return Intr.getNode();
2007}
2008
2009// CC is a comparison that will be implemented using an integer or
2010// floating-point comparison. Return the condition code mask for
2011// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2012// unsigned comparisons and clear for signed ones. In the floating-point
2013// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2014static unsigned CCMaskForCondCode(ISD::CondCode CC) {
2015#define CONV(X) \
2016 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2017 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2018 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2019
2020 switch (CC) {
2021 default:
2022 llvm_unreachable("Invalid integer condition!");
2023
2024 CONV(EQ);
2025 CONV(NE);
2026 CONV(GT);
2027 CONV(GE);
2028 CONV(LT);
2029 CONV(LE);
2030
2031 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2032 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
2033 }
2034#undef CONV
2035}
2036
2037// If C can be converted to a comparison against zero, adjust the operands
2038// as necessary.
2039static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2040 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2041 return;
2042
2043 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
2044 if (!ConstOp1)
2045 return;
2046
2047 int64_t Value = ConstOp1->getSExtValue();
2048 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
2049 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
2050 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
2051 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
2052 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2053 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
2054 }
2055}
2056
2057// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
2058// adjust the operands as necessary.
2059static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
2060 Comparison &C) {
2061 // For us to make any changes, it must a comparison between a single-use
2062 // load and a constant.
2063 if (!C.Op0.hasOneUse() ||
2064 C.Op0.getOpcode() != ISD::LOAD ||
2065 C.Op1.getOpcode() != ISD::Constant)
2066 return;
2067
2068 // We must have an 8- or 16-bit load.
2069 auto *Load = cast<LoadSDNode>(C.Op0);
2070 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
2071 if ((NumBits != 8 && NumBits != 16) ||
2072 NumBits != Load->getMemoryVT().getStoreSizeInBits())
2073 return;
2074
2075 // The load must be an extending one and the constant must be within the
2076 // range of the unextended value.
2077 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2078 uint64_t Value = ConstOp1->getZExtValue();
2079 uint64_t Mask = (1 << NumBits) - 1;
2080 if (Load->getExtensionType() == ISD::SEXTLOAD) {
2081 // Make sure that ConstOp1 is in range of C.Op0.
2082 int64_t SignedValue = ConstOp1->getSExtValue();
2083 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
2084 return;
2085 if (C.ICmpType != SystemZICMP::SignedOnly) {
2086 // Unsigned comparison between two sign-extended values is equivalent
2087 // to unsigned comparison between two zero-extended values.
2088 Value &= Mask;
2089 } else if (NumBits == 8) {
2090 // Try to treat the comparison as unsigned, so that we can use CLI.
2091 // Adjust CCMask and Value as necessary.
2092 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
2093 // Test whether the high bit of the byte is set.
2094 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
2095 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
2096 // Test whether the high bit of the byte is clear.
2097 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
2098 else
2099 // No instruction exists for this combination.
2100 return;
2101 C.ICmpType = SystemZICMP::UnsignedOnly;
2102 }
2103 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
2104 if (Value > Mask)
2105 return;
2106 // If the constant is in range, we can use any comparison.
2107 C.ICmpType = SystemZICMP::Any;
2108 } else
2109 return;
2110
2111 // Make sure that the first operand is an i32 of the right extension type.
2112 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
2113 ISD::SEXTLOAD :
2114 ISD::ZEXTLOAD);
2115 if (C.Op0.getValueType() != MVT::i32 ||
2116 Load->getExtensionType() != ExtType) {
2117 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
2118 Load->getBasePtr(), Load->getPointerInfo(),
2119 Load->getMemoryVT(), Load->getAlignment(),
2120 Load->getMemOperand()->getFlags());
2121 // Update the chain uses.
2122 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
2123 }
2124
2125 // Make sure that the second operand is an i32 with the right value.
2126 if (C.Op1.getValueType() != MVT::i32 ||
2127 Value != ConstOp1->getZExtValue())
2128 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
2129}
2130
2131// Return true if Op is either an unextended load, or a load suitable
2132// for integer register-memory comparisons of type ICmpType.
2133static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
2134 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
2135 if (Load) {
2136 // There are no instructions to compare a register with a memory byte.
2137 if (Load->getMemoryVT() == MVT::i8)
2138 return false;
2139 // Otherwise decide on extension type.
2140 switch (Load->getExtensionType()) {
2141 case ISD::NON_EXTLOAD:
2142 return true;
2143 case ISD::SEXTLOAD:
2144 return ICmpType != SystemZICMP::UnsignedOnly;
2145 case ISD::ZEXTLOAD:
2146 return ICmpType != SystemZICMP::SignedOnly;
2147 default:
2148 break;
2149 }
2150 }
2151 return false;
2152}
2153
2154// Return true if it is better to swap the operands of C.
2155static bool shouldSwapCmpOperands(const Comparison &C) {
2156 // Leave f128 comparisons alone, since they have no memory forms.
2157 if (C.Op0.getValueType() == MVT::f128)
2158 return false;
2159
2160 // Always keep a floating-point constant second, since comparisons with
2161 // zero can use LOAD TEST and comparisons with other constants make a
2162 // natural memory operand.
2163 if (isa<ConstantFPSDNode>(C.Op1))
2164 return false;
2165
2166 // Never swap comparisons with zero since there are many ways to optimize
2167 // those later.
2168 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2169 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
2170 return false;
2171
2172 // Also keep natural memory operands second if the loaded value is
2173 // only used here. Several comparisons have memory forms.
2174 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
2175 return false;
2176
2177 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
2178 // In that case we generally prefer the memory to be second.
2179 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
2180 // The only exceptions are when the second operand is a constant and
2181 // we can use things like CHHSI.
2182 if (!ConstOp1)
2183 return true;
2184 // The unsigned memory-immediate instructions can handle 16-bit
2185 // unsigned integers.
2186 if (C.ICmpType != SystemZICMP::SignedOnly &&
2187 isUInt<16>(ConstOp1->getZExtValue()))
2188 return false;
2189 // The signed memory-immediate instructions can handle 16-bit
2190 // signed integers.
2191 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
2192 isInt<16>(ConstOp1->getSExtValue()))
2193 return false;
2194 return true;
2195 }
2196
2197 // Try to promote the use of CGFR and CLGFR.
2198 unsigned Opcode0 = C.Op0.getOpcode();
2199 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
2200 return true;
2201 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
2202 return true;
2203 if (C.ICmpType != SystemZICMP::SignedOnly &&
2204 Opcode0 == ISD::AND &&
2205 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
2206 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
2207 return true;
2208
2209 return false;
2210}
2211
2212// Check whether C tests for equality between X and Y and whether X - Y
2213// or Y - X is also computed. In that case it's better to compare the
2214// result of the subtraction against zero.
2215static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
2216 Comparison &C) {
2217 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2218 C.CCMask == SystemZ::CCMASK_CMP_NE) {
2219 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
2220 SDNode *N = *I;
2221 if (N->getOpcode() == ISD::SUB &&
2222 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
2223 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
2224 C.Op0 = SDValue(N, 0);
2225 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
2226 return;
2227 }
2228 }
2229 }
2230}
2231
2232// Check whether C compares a floating-point value with zero and if that
2233// floating-point value is also negated. In this case we can use the
2234// negation to set CC, so avoiding separate LOAD AND TEST and
2235// LOAD (NEGATIVE/COMPLEMENT) instructions.
2236static void adjustForFNeg(Comparison &C) {
2237 // This optimization is invalid for strict comparisons, since FNEG
2238 // does not raise any exceptions.
2239 if (C.Chain)
2240 return;
2241 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
2242 if (C1 && C1->isZero()) {
2243 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
2244 SDNode *N = *I;
2245 if (N->getOpcode() == ISD::FNEG) {
2246 C.Op0 = SDValue(N, 0);
2247 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
2248 return;
2249 }
2250 }
2251 }
2252}
2253
2254// Check whether C compares (shl X, 32) with 0 and whether X is
2255// also sign-extended. In that case it is better to test the result
2256// of the sign extension using LTGFR.
2257//
2258// This case is important because InstCombine transforms a comparison
2259// with (sext (trunc X)) into a comparison with (shl X, 32).
2260static void adjustForLTGFR(Comparison &C) {
2261 // Check for a comparison between (shl X, 32) and 0.
2262 if (C.Op0.getOpcode() == ISD::SHL &&
2263 C.Op0.getValueType() == MVT::i64 &&
2264 C.Op1.getOpcode() == ISD::Constant &&
2265 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2266 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2267 if (C1 && C1->getZExtValue() == 32) {
2268 SDValue ShlOp0 = C.Op0.getOperand(0);
2269 // See whether X has any SIGN_EXTEND_INREG uses.
2270 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
2271 SDNode *N = *I;
2272 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
2273 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
2274 C.Op0 = SDValue(N, 0);
2275 return;
2276 }
2277 }
2278 }
2279 }
2280}
2281
2282// If C compares the truncation of an extending load, try to compare
2283// the untruncated value instead. This exposes more opportunities to
2284// reuse CC.
2285static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
2286 Comparison &C) {
2287 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
2288 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
2289 C.Op1.getOpcode() == ISD::Constant &&
2290 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2291 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
2292 if (L->getMemoryVT().getStoreSizeInBits().getFixedSize() <=
2293 C.Op0.getValueSizeInBits().getFixedSize()) {
2294 unsigned Type = L->getExtensionType();
2295 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
2296 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
2297 C.Op0 = C.Op0.getOperand(0);
2298 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
2299 }
2300 }
2301 }
2302}
2303
2304// Return true if shift operation N has an in-range constant shift value.
2305// Store it in ShiftVal if so.
2306static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
2307 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
2308 if (!Shift)
2309 return false;
2310
2311 uint64_t Amount = Shift->getZExtValue();
2312 if (Amount >= N.getValueSizeInBits())
2313 return false;
2314
2315 ShiftVal = Amount;
2316 return true;
2317}
2318
2319// Check whether an AND with Mask is suitable for a TEST UNDER MASK
2320// instruction and whether the CC value is descriptive enough to handle
2321// a comparison of type Opcode between the AND result and CmpVal.
2322// CCMask says which comparison result is being tested and BitSize is
2323// the number of bits in the operands. If TEST UNDER MASK can be used,
2324// return the corresponding CC mask, otherwise return 0.
2325static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
2326 uint64_t Mask, uint64_t CmpVal,
2327 unsigned ICmpType) {
2328 assert(Mask != 0 && "ANDs with zero should have been removed by now");
2329
2330 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
2331 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
2332 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
2333 return 0;
2334
2335 // Work out the masks for the lowest and highest bits.
2336 unsigned HighShift = 63 - countLeadingZeros(Mask);
2337 uint64_t High = uint64_t(1) << HighShift;
2338 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
2339
2340 // Signed ordered comparisons are effectively unsigned if the sign
2341 // bit is dropped.
2342 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
2343
2344 // Check for equality comparisons with 0, or the equivalent.
2345 if (CmpVal == 0) {
2346 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2347 return SystemZ::CCMASK_TM_ALL_0;
2348 if (CCMask == SystemZ::CCMASK_CMP_NE)
2349 return SystemZ::CCMASK_TM_SOME_1;
2350 }
2351 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2352 if (CCMask == SystemZ::CCMASK_CMP_LT)
2353 return SystemZ::CCMASK_TM_ALL_0;
2354 if (CCMask == SystemZ::CCMASK_CMP_GE)
2355 return SystemZ::CCMASK_TM_SOME_1;
2356 }
2357 if (EffectivelyUnsigned && CmpVal < Low) {
2358 if (CCMask == SystemZ::CCMASK_CMP_LE)
2359 return SystemZ::CCMASK_TM_ALL_0;
2360 if (CCMask == SystemZ::CCMASK_CMP_GT)
2361 return SystemZ::CCMASK_TM_SOME_1;
2362 }
2363
2364 // Check for equality comparisons with the mask, or the equivalent.
2365 if (CmpVal == Mask) {
2366 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2367 return SystemZ::CCMASK_TM_ALL_1;
2368 if (CCMask == SystemZ::CCMASK_CMP_NE)
2369 return SystemZ::CCMASK_TM_SOME_0;
2370 }
2371 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2372 if (CCMask == SystemZ::CCMASK_CMP_GT)
2373 return SystemZ::CCMASK_TM_ALL_1;
2374 if (CCMask == SystemZ::CCMASK_CMP_LE)
2375 return SystemZ::CCMASK_TM_SOME_0;
2376 }
2377 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2378 if (CCMask == SystemZ::CCMASK_CMP_GE)
2379 return SystemZ::CCMASK_TM_ALL_1;
2380 if (CCMask == SystemZ::CCMASK_CMP_LT)
2381 return SystemZ::CCMASK_TM_SOME_0;
2382 }
2383
2384 // Check for ordered comparisons with the top bit.
2385 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2386 if (CCMask == SystemZ::CCMASK_CMP_LE)
2387 return SystemZ::CCMASK_TM_MSB_0;
2388 if (CCMask == SystemZ::CCMASK_CMP_GT)
2389 return SystemZ::CCMASK_TM_MSB_1;
2390 }
2391 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2392 if (CCMask == SystemZ::CCMASK_CMP_LT)
2393 return SystemZ::CCMASK_TM_MSB_0;
2394 if (CCMask == SystemZ::CCMASK_CMP_GE)
2395 return SystemZ::CCMASK_TM_MSB_1;
2396 }
2397
2398 // If there are just two bits, we can do equality checks for Low and High
2399 // as well.
2400 if (Mask == Low + High) {
2401 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2402 return SystemZ::CCMASK_TM_MIXED_MSB_0;
2403 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2404 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
2405 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2406 return SystemZ::CCMASK_TM_MIXED_MSB_1;
2407 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2408 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
2409 }
2410
2411 // Looks like we've exhausted our options.
2412 return 0;
2413}
2414
2415// See whether C can be implemented as a TEST UNDER MASK instruction.
2416// Update the arguments with the TM version if so.
2417static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2418 Comparison &C) {
2419 // Check that we have a comparison with a constant.
2420 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2421 if (!ConstOp1)
2422 return;
2423 uint64_t CmpVal = ConstOp1->getZExtValue();
2424
2425 // Check whether the nonconstant input is an AND with a constant mask.
2426 Comparison NewC(C);
2427 uint64_t MaskVal;
2428 ConstantSDNode *Mask = nullptr;
2429 if (C.Op0.getOpcode() == ISD::AND) {
2430 NewC.Op0 = C.Op0.getOperand(0);
2431 NewC.Op1 = C.Op0.getOperand(1);
2432 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2433 if (!Mask)
2434 return;
2435 MaskVal = Mask->getZExtValue();
2436 } else {
2437 // There is no instruction to compare with a 64-bit immediate
2438 // so use TMHH instead if possible. We need an unsigned ordered
2439 // comparison with an i64 immediate.
2440 if (NewC.Op0.getValueType() != MVT::i64 ||
2441 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2442 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2443 NewC.ICmpType == SystemZICMP::SignedOnly)
2444 return;
2445 // Convert LE and GT comparisons into LT and GE.
2446 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2447 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2448 if (CmpVal == uint64_t(-1))
2449 return;
2450 CmpVal += 1;
2451 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2452 }
2453 // If the low N bits of Op1 are zero than the low N bits of Op0 can
2454 // be masked off without changing the result.
2455 MaskVal = -(CmpVal & -CmpVal);
2456 NewC.ICmpType = SystemZICMP::UnsignedOnly;
2457 }
2458 if (!MaskVal)
2459 return;
2460
2461 // Check whether the combination of mask, comparison value and comparison
2462 // type are suitable.
2463 unsigned BitSize = NewC.Op0.getValueSizeInBits();
2464 unsigned NewCCMask, ShiftVal;
2465 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2466 NewC.Op0.getOpcode() == ISD::SHL &&
2467 isSimpleShift(NewC.Op0, ShiftVal) &&
2468 (MaskVal >> ShiftVal != 0) &&
2469 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
2470 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2471 MaskVal >> ShiftVal,
2472 CmpVal >> ShiftVal,
2473 SystemZICMP::Any))) {
2474 NewC.Op0 = NewC.Op0.getOperand(0);
2475 MaskVal >>= ShiftVal;
2476 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2477 NewC.Op0.getOpcode() == ISD::SRL &&
2478 isSimpleShift(NewC.Op0, ShiftVal) &&
2479 (MaskVal << ShiftVal != 0) &&
2480 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
2481 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2482 MaskVal << ShiftVal,
2483 CmpVal << ShiftVal,
2484 SystemZICMP::UnsignedOnly))) {
2485 NewC.Op0 = NewC.Op0.getOperand(0);
2486 MaskVal <<= ShiftVal;
2487 } else {
2488 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2489 NewC.ICmpType);
2490 if (!NewCCMask)
2491 return;
2492 }
2493
2494 // Go ahead and make the change.
2495 C.Opcode = SystemZISD::TM;
2496 C.Op0 = NewC.Op0;
2497 if (Mask && Mask->getZExtValue() == MaskVal)
2498 C.Op1 = SDValue(Mask, 0);
2499 else
2500 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2501 C.CCValid = SystemZ::CCMASK_TM;
2502 C.CCMask = NewCCMask;
2503}
2504
2505// See whether the comparison argument contains a redundant AND
2506// and remove it if so. This sometimes happens due to the generic
2507// BRCOND expansion.
2508static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL,
2509 Comparison &C) {
2510 if (C.Op0.getOpcode() != ISD::AND)
2511 return;
2512 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2513 if (!Mask)
2514 return;
2515 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
2516 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
2517 return;
2518
2519 C.Op0 = C.Op0.getOperand(0);
2520}
2521
2522// Return a Comparison that tests the condition-code result of intrinsic
2523// node Call against constant integer CC using comparison code Cond.
2524// Opcode is the opcode of the SystemZISD operation for the intrinsic
2525// and CCValid is the set of possible condition-code results.
2526static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2527 SDValue Call, unsigned CCValid, uint64_t CC,
2528 ISD::CondCode Cond) {
2529 Comparison C(Call, SDValue(), SDValue());
2530 C.Opcode = Opcode;
2531 C.CCValid = CCValid;
2532 if (Cond == ISD::SETEQ)
2533 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2534 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2535 else if (Cond == ISD::SETNE)
2536 // ...and the inverse of that.
2537 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2538 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2539 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2540 // always true for CC>3.
2541 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2542 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2543 // ...and the inverse of that.
2544 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2545 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2546 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2547 // always true for CC>3.
2548 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2549 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2550 // ...and the inverse of that.
2551 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2552 else
2553 llvm_unreachable("Unexpected integer comparison type");
2554 C.CCMask &= CCValid;
2555 return C;
2556}
2557
2558// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2559static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2560 ISD::CondCode Cond, const SDLoc &DL,
2561 SDValue Chain = SDValue(),
2562 bool IsSignaling = false) {
2563 if (CmpOp1.getOpcode() == ISD::Constant) {
2564 assert(!Chain);
2565 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2566 unsigned Opcode, CCValid;
2567 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2568 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2569 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2570 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2571 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2572 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2573 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2574 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2575 }
2576 Comparison C(CmpOp0, CmpOp1, Chain);
2577 C.CCMask = CCMaskForCondCode(Cond);
2578 if (C.Op0.getValueType().isFloatingPoint()) {
2579 C.CCValid = SystemZ::CCMASK_FCMP;
2580 if (!C.Chain)
2581 C.Opcode = SystemZISD::FCMP;
2582 else if (!IsSignaling)
2583 C.Opcode = SystemZISD::STRICT_FCMP;
2584 else
2585 C.Opcode = SystemZISD::STRICT_FCMPS;
2586 adjustForFNeg(C);
2587 } else {
2588 assert(!C.Chain);
2589 C.CCValid = SystemZ::CCMASK_ICMP;
2590 C.Opcode = SystemZISD::ICMP;
2591 // Choose the type of comparison. Equality and inequality tests can
2592 // use either signed or unsigned comparisons. The choice also doesn't
2593 // matter if both sign bits are known to be clear. In those cases we
2594 // want to give the main isel code the freedom to choose whichever
2595 // form fits best.
2596 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2597 C.CCMask == SystemZ::CCMASK_CMP_NE ||
2598 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2599 C.ICmpType = SystemZICMP::Any;
2600 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2601 C.ICmpType = SystemZICMP::UnsignedOnly;
2602 else
2603 C.ICmpType = SystemZICMP::SignedOnly;
2604 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2605 adjustForRedundantAnd(DAG, DL, C);
2606 adjustZeroCmp(DAG, DL, C);
2607 adjustSubwordCmp(DAG, DL, C);
2608 adjustForSubtraction(DAG, DL, C);
2609 adjustForLTGFR(C);
2610 adjustICmpTruncate(DAG, DL, C);
2611 }
2612
2613 if (shouldSwapCmpOperands(C)) {
2614 std::swap(C.Op0, C.Op1);
2615 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
2616 }
2617
2618 adjustForTestUnderMask(DAG, DL, C);
2619 return C;
2620}
2621
2622// Emit the comparison instruction described by C.
2623static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2624 if (!C.Op1.getNode()) {
2625 SDNode *Node;
2626 switch (C.Op0.getOpcode()) {
2627 case ISD::INTRINSIC_W_CHAIN:
2628 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
2629 return SDValue(Node, 0);
2630 case ISD::INTRINSIC_WO_CHAIN:
2631 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
2632 return SDValue(Node, Node->getNumValues() - 1);
2633 default:
2634 llvm_unreachable("Invalid comparison operands");
2635 }
2636 }
2637 if (C.Opcode == SystemZISD::ICMP)
2638 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
2639 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
2640 if (C.Opcode == SystemZISD::TM) {
2641 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2642 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2643 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
2644 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
2645 }
2646 if (C.Chain) {
2647 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
2648 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
2649 }
2650 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
2651}
2652
2653// Implement a 32-bit *MUL_LOHI operation by extending both operands to
2654// 64 bits. Extend is the extension type to use. Store the high part
2655// in Hi and the low part in Lo.
2656static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2657 SDValue Op0, SDValue Op1, SDValue &Hi,
2658 SDValue &Lo) {
2659 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2660 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2661 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2662 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2663 DAG.getConstant(32, DL, MVT::i64));
2664 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2665 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2666}
2667
2668// Lower a binary operation that produces two VT results, one in each
2669// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2670// and Opcode performs the GR128 operation. Store the even register result
2671// in Even and the odd register result in Odd.
2672static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2673 unsigned Opcode, SDValue Op0, SDValue Op1,
2674 SDValue &Even, SDValue &Odd) {
2675 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
2676 bool Is32Bit = is32Bit(VT);
2677 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2678 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2679}
2680
2681// Return an i32 value that is 1 if the CC value produced by CCReg is
2682// in the mask CCMask and 0 otherwise. CC is known to have a value
2683// in CCValid, so other values can be ignored.
2684static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
2685 unsigned CCValid, unsigned CCMask) {
2686 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
2687 DAG.getConstant(0, DL, MVT::i32),
2688 DAG.getTargetConstant(CCValid, DL, MVT::i32),
2689 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
2690 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
2691}
2692
2693// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2694// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
2695// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
2696// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
2697// floating-point comparisons.
2698enum class CmpMode { Int, FP, StrictFP, SignalingFP };
2699static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode) {
2700 switch (CC) {
2701 case ISD::SETOEQ:
2702 case ISD::SETEQ:
2703 switch (Mode) {
2704 case CmpMode::Int: return SystemZISD::VICMPE;
2705 case CmpMode::FP: return SystemZISD::VFCMPE;
2706 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
2707 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
2708 }
2709 llvm_unreachable("Bad mode");
2710
2711 case ISD::SETOGE:
2712 case ISD::SETGE:
2713 switch (Mode) {
2714 case CmpMode::Int: return 0;
2715 case CmpMode::FP: return SystemZISD::VFCMPHE;
2716 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
2717 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
2718 }
2719 llvm_unreachable("Bad mode");
2720
2721 case ISD::SETOGT:
2722 case ISD::SETGT:
2723 switch (Mode) {
2724 case CmpMode::Int: return SystemZISD::VICMPH;
2725 case CmpMode::FP: return SystemZISD::VFCMPH;
2726 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
2727 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
2728 }
2729 llvm_unreachable("Bad mode");
2730
2731 case ISD::SETUGT:
2732 switch (Mode) {
2733 case CmpMode::Int: return SystemZISD::VICMPHL;
2734 case CmpMode::FP: return 0;
2735 case CmpMode::StrictFP: return 0;
2736 case CmpMode::SignalingFP: return 0;
2737 }
2738 llvm_unreachable("Bad mode");
2739
2740 default:
2741 return 0;
2742 }
2743}
2744
2745// Return the SystemZISD vector comparison operation for CC or its inverse,
2746// or 0 if neither can be done directly. Indicate in Invert whether the
2747// result is for the inverse of CC. Mode is as above.
2748static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode,
2749 bool &Invert) {
2750 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2751 Invert = false;
2752 return Opcode;
2753 }
2754
2755 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
2756 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2757 Invert = true;
2758 return Opcode;
2759 }
2760
2761 return 0;
2762}
2763
2764// Return a v2f64 that contains the extended form of elements Start and Start+1
2765// of v4f32 value Op. If Chain is nonnull, return the strict form.
2766static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2767 SDValue Op, SDValue Chain) {
2768 int Mask[] = { Start, -1, Start + 1, -1 };
2769 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2770 if (Chain) {
2771 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
2772 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
2773 }
2774 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2775}
2776
2777// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2778// producing a result of type VT. If Chain is nonnull, return the strict form.
2779SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
2780 const SDLoc &DL, EVT VT,
2781 SDValue CmpOp0,
2782 SDValue CmpOp1,
2783 SDValue Chain) const {
2784 // There is no hardware support for v4f32 (unless we have the vector
2785 // enhancements facility 1), so extend the vector into two v2f64s
2786 // and compare those.
2787 if (CmpOp0.getValueType() == MVT::v4f32 &&
2788 !Subtarget.hasVectorEnhancements1()) {
2789 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
2790 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
2791 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
2792 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
2793 if (Chain) {
2794 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
2795 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
2796 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
2797 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2798 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
2799 H1.getValue(1), L1.getValue(1),
2800 HRes.getValue(1), LRes.getValue(1) };
2801 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2802 SDValue Ops[2] = { Res, NewChain };
2803 return DAG.getMergeValues(Ops, DL);
2804 }
2805 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2806 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2807 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2808 }
2809 if (Chain) {
2810 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2811 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
2812 }
2813 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2814}
2815
2816// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2817// an integer mask of type VT. If Chain is nonnull, we have a strict
2818// floating-point comparison. If in addition IsSignaling is true, we have
2819// a strict signaling floating-point comparison.
2820SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
2821 const SDLoc &DL, EVT VT,
2822 ISD::CondCode CC,
2823 SDValue CmpOp0,
2824 SDValue CmpOp1,
2825 SDValue Chain,
2826 bool IsSignaling) const {
2827 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2828 assert (!Chain || IsFP);
2829 assert (!IsSignaling || Chain);
2830 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
2831 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
2832 bool Invert = false;
2833 SDValue Cmp;
2834 switch (CC) {
2835 // Handle tests for order using (or (ogt y x) (oge x y)).
2836 case ISD::SETUO:
2837 Invert = true;
2838 LLVM_FALLTHROUGH;
2839 case ISD::SETO: {
2840 assert(IsFP && "Unexpected integer comparison");
2841 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2842 DL, VT, CmpOp1, CmpOp0, Chain);
2843 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
2844 DL, VT, CmpOp0, CmpOp1, Chain);
2845 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2846 if (Chain)
2847 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2848 LT.getValue(1), GE.getValue(1));
2849 break;
2850 }
2851
2852 // Handle <> tests using (or (ogt y x) (ogt x y)).
2853 case ISD::SETUEQ:
2854 Invert = true;
2855 LLVM_FALLTHROUGH;
2856 case ISD::SETONE: {
2857 assert(IsFP && "Unexpected integer comparison");
2858 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2859 DL, VT, CmpOp1, CmpOp0, Chain);
2860 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2861 DL, VT, CmpOp0, CmpOp1, Chain);
2862 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2863 if (Chain)
2864 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2865 LT.getValue(1), GT.getValue(1));
2866 break;
2867 }
2868
2869 // Otherwise a single comparison is enough. It doesn't really
2870 // matter whether we try the inversion or the swap first, since
2871 // there are no cases where both work.
2872 default:
2873 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
2874 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
2875 else {
2876 CC = ISD::getSetCCSwappedOperands(CC);
2877 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
2878 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
2879 else
2880 llvm_unreachable("Unhandled comparison");
2881 }
2882 if (Chain)
2883 Chain = Cmp.getValue(1);
2884 break;
2885 }
2886 if (Invert) {
2887 SDValue Mask =
2888 DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64));
2889 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2890 }
2891 if (Chain && Chain.getNode() != Cmp.getNode()) {
2892 SDValue Ops[2] = { Cmp, Chain };
2893 Cmp = DAG.getMergeValues(Ops, DL);
2894 }
2895 return Cmp;
2896}
2897
2898SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2899 SelectionDAG &DAG) const {
2900 SDValue CmpOp0 = Op.getOperand(0);
2901 SDValue CmpOp1 = Op.getOperand(1);
2902 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2903 SDLoc DL(Op);
2904 EVT VT = Op.getValueType();
2905 if (VT.isVector())
2906 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2907
2908 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2909 SDValue CCReg = emitCmp(DAG, DL, C);
2910 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
2911}
2912
2913SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
2914 SelectionDAG &DAG,
2915 bool IsSignaling) const {
2916 SDValue Chain = Op.getOperand(0);
2917 SDValue CmpOp0 = Op.getOperand(1);
2918 SDValue CmpOp1 = Op.getOperand(2);
2919 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
2920 SDLoc DL(Op);
2921 EVT VT = Op.getNode()->getValueType(0);
2922 if (VT.isVector()) {
2923 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
2924 Chain, IsSignaling);
2925 return Res.getValue(Op.getResNo());
2926 }
2927
2928 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
2929 SDValue CCReg = emitCmp(DAG, DL, C);
2930 CCReg->setFlags(Op->getFlags());
2931 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
2932 SDValue Ops[2] = { Result, CCReg.getValue(1) };
2933 return DAG.getMergeValues(Ops, DL);
2934}
2935
2936SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2937 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2938 SDValue CmpOp0 = Op.getOperand(2);
2939 SDValue CmpOp1 = Op.getOperand(3);
2940 SDValue Dest = Op.getOperand(4);
2941 SDLoc DL(Op);
2942
2943 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2944 SDValue CCReg = emitCmp(DAG, DL, C);
2945 return DAG.getNode(
2946 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
2947 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
2948 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
2949}
2950
2951// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2952// allowing Pos and Neg to be wider than CmpOp.
2953static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2954 return (Neg.getOpcode() == ISD::SUB &&
2955 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2956 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2957 Neg.getOperand(1) == Pos &&
2958 (Pos == CmpOp ||
2959 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2960 Pos.getOperand(0) == CmpOp)));
2961}
2962
2963// Return the absolute or negative absolute of Op; IsNegative decides which.
2964static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2965 bool IsNegative) {
2966 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
2967 if (IsNegative)
2968 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2969 DAG.getConstant(0, DL, Op.getValueType()), Op);
2970 return Op;
2971}
2972
2973SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2974 SelectionDAG &DAG) const {
2975 SDValue CmpOp0 = Op.getOperand(0);
2976 SDValue CmpOp1 = Op.getOperand(1);
2977 SDValue TrueOp = Op.getOperand(2);
2978 SDValue FalseOp = Op.getOperand(3);
2979 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2980 SDLoc DL(Op);
2981
2982 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2983
2984 // Check for absolute and negative-absolute selections, including those
2985 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2986 // This check supplements the one in DAGCombiner.
2987 if (C.Opcode == SystemZISD::ICMP &&
2988 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2989 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2990 C.Op1.getOpcode() == ISD::Constant &&
2991 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2992 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2993 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2994 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2995 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2996 }
2997
2998 SDValue CCReg = emitCmp(DAG, DL, C);
2999 SDValue Ops[] = {TrueOp, FalseOp,
3000 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
3001 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
3002
3003 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
3004}
3005
3006SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
3007 SelectionDAG &DAG) const {
3008 SDLoc DL(Node);
3009 const GlobalValue *GV = Node->getGlobal();
3010 int64_t Offset = Node->getOffset();
3011 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3012 CodeModel::Model CM = DAG.getTarget().getCodeModel();
3013
3014 SDValue Result;
3015 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
3016 if (isInt<32>(Offset)) {
3017 // Assign anchors at 1<<12 byte boundaries.
3018 uint64_t Anchor = Offset & ~uint64_t(0xfff);
3019 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
3020 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3021
3022 // The offset can be folded into the address if it is aligned to a
3023 // halfword.
3024 Offset -= Anchor;
3025 if (Offset != 0 && (Offset & 1) == 0) {
3026 SDValue Full =
3027 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
3028 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
3029 Offset = 0;
3030 }
3031 } else {
3032 // Conservatively load a constant offset greater than 32 bits into a
3033 // register below.
3034 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
3035 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3036 }
3037 } else {
3038 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
3039 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3040 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3041 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3042 }
3043
3044 // If there was a non-zero offset that we didn't fold, create an explicit
3045 // addition for it.
3046 if (Offset != 0)
3047 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
3048 DAG.getConstant(Offset, DL, PtrVT));
3049
3050 return Result;
3051}
3052
3053SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
3054 SelectionDAG &DAG,
3055 unsigned Opcode,
3056 SDValue GOTOffset) const {
3057 SDLoc DL(Node);
3058 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3059 SDValue Chain = DAG.getEntryNode();
3060 SDValue Glue;
3061
3062 if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3063 CallingConv::GHC)
3064 report_fatal_error("In GHC calling convention TLS is not supported");
3065
3066 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
3067 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
3068 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
3069 Glue = Chain.getValue(1);
3070 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
3071 Glue = Chain.getValue(1);
3072
3073 // The first call operand is the chain and the second is the TLS symbol.
3074 SmallVector<SDValue, 8> Ops;
3075 Ops.push_back(Chain);
3076 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
3077 Node->getValueType(0),
3078 0, 0));
3079
3080 // Add argument registers to the end of the list so that they are
3081 // known live into the call.
3082 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
3083 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
3084
3085 // Add a register mask operand representing the call-preserved registers.
3086 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3087 const uint32_t *Mask =
3088 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3089 assert(Mask && "Missing call preserved mask for calling convention");
3090 Ops.push_back(DAG.getRegisterMask(Mask));
3091
3092 // Glue the call to the argument copies.
3093 Ops.push_back(Glue);
3094
3095 // Emit the call.
3096 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3097 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
3098 Glue = Chain.getValue(1);
3099
3100 // Copy the return value from %r2.
3101 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
3102}
3103
3104SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
3105 SelectionDAG &DAG) const {
3106 SDValue Chain = DAG.getEntryNode();
3107 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3108
3109 // The high part of the thread pointer is in access register 0.
3110 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
3111 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
3112
3113 // The low part of the thread pointer is in access register 1.
3114 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
3115 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
3116
3117 // Merge them into a single 64-bit address.
3118 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
3119 DAG.getConstant(32, DL, PtrVT));
3120 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
3121}
3122
3123SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
3124 SelectionDAG &DAG) const {
3125 if (DAG.getTarget().useEmulatedTLS())
3126 return LowerToTLSEmulatedModel(Node, DAG);
3127 SDLoc DL(Node);
3128 const GlobalValue *GV = Node->getGlobal();
3129 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3130 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
3131
3132 if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3133 CallingConv::GHC)
3134 report_fatal_error("In GHC calling convention TLS is not supported");
3135
3136 SDValue TP = lowerThreadPointer(DL, DAG);
3137
3138 // Get the offset of GA from the thread pointer, based on the TLS model.
3139 SDValue Offset;
3140 switch (model) {
3141 case TLSModel::GeneralDynamic: {
3142 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
3143 SystemZConstantPoolValue *CPV =
3144 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
3145
3146 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3147 Offset = DAG.getLoad(
3148 PtrVT, DL, DAG.getEntryNode(), Offset,
3149 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3150
3151 // Call __tls_get_offset to retrieve the offset.
3152 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
3153 break;
3154 }
3155
3156 case TLSModel::LocalDynamic: {
3157 // Load the GOT offset of the module ID.
3158 SystemZConstantPoolValue *CPV =
3159 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
3160
3161 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3162 Offset = DAG.getLoad(
3163 PtrVT, DL, DAG.getEntryNode(), Offset,
3164 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3165
3166 // Call __tls_get_offset to retrieve the module base offset.
3167 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
3168
3169 // Note: The SystemZLDCleanupPass will remove redundant computations
3170 // of the module base offset. Count total number of local-dynamic
3171 // accesses to trigger execution of that pass.
3172 SystemZMachineFunctionInfo* MFI =
3173 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
3174 MFI->incNumLocalDynamicTLSAccesses();
3175
3176 // Add the per-symbol offset.
3177 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
3178
3179 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3180 DTPOffset = DAG.getLoad(
3181 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
3182 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3183
3184 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
3185 break;
3186 }
3187
3188 case TLSModel::InitialExec: {
3189 // Load the offset from the GOT.
3190 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3191 SystemZII::MO_INDNTPOFF);
3192 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
3193 Offset =
3194 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
3195 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3196 break;
3197 }
3198
3199 case TLSModel::LocalExec: {
3200 // Force the offset into the constant pool and load it from there.
3201 SystemZConstantPoolValue *CPV =
3202 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
3203
3204 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3205 Offset = DAG.getLoad(
3206 PtrVT, DL, DAG.getEntryNode(), Offset,
3207 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3208 break;
3209 }
3210 }
3211
3212 // Add the base and offset together.
3213 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
3214}
3215
3216SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
3217 SelectionDAG &DAG) const {
3218 SDLoc DL(Node);
3219 const BlockAddress *BA = Node->getBlockAddress();
3220 int64_t Offset = Node->getOffset();
3221 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3222
3223 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
3224 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3225 return Result;
3226}
3227
3228SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
3229 SelectionDAG &DAG) const {
3230 SDLoc DL(JT);
3231 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3232 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3233
3234 // Use LARL to load the address of the table.
3235 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3236}
3237
3238SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
3239 SelectionDAG &DAG) const {
3240 SDLoc DL(CP);
3241 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3242
3243 SDValue Result;
3244 if (CP->isMachineConstantPoolEntry())
3245 Result =
3246 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3247 else
3248 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
3249 CP->getOffset());
3250
3251 // Use LARL to load the address of the constant pool entry.
3252 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3253}
3254
3255SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
3256 SelectionDAG &DAG) const {
3257 auto *TFL =
3258 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
3259 MachineFunction &MF = DAG.getMachineFunction();
3260 MachineFrameInfo &MFI = MF.getFrameInfo();
3261 MFI.setFrameAddressIsTaken(true);
3262
3263 SDLoc DL(Op);
3264 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3265 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3266
3267 // Return null if the back chain is not present.
3268 bool HasBackChain = MF.getFunction().hasFnAttribute("backchain");
3269 if (TFL->usePackedStack(MF) && !HasBackChain)
3270 return DAG.getConstant(0, DL, PtrVT);
3271
3272 // By definition, the frame address is the address of the back chain.
3273 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
3274 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
3275
3276 // FIXME The frontend should detect this case.
3277 if (Depth > 0) {
3278 report_fatal_error("Unsupported stack frame traversal count");
3279 }
3280
3281 return BackChain;
3282}
3283
3284SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
3285 SelectionDAG &DAG) const {
3286 MachineFunction &MF = DAG.getMachineFunction();
3287 MachineFrameInfo &MFI = MF.getFrameInfo();
3288 MFI.setReturnAddressIsTaken(true);
3289
3290 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3291 return SDValue();
3292
3293 SDLoc DL(Op);
3294 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3295 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3296
3297 // FIXME The frontend should detect this case.
3298 if (Depth > 0) {
3299 report_fatal_error("Unsupported stack frame traversal count");
3300 }
3301
3302 // Return R14D, which has the return address. Mark it an implicit live-in.
3303 unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
3304 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
3305}
3306
3307SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
3308 SelectionDAG &DAG) const {
3309 SDLoc DL(Op);
3310 SDValue In = Op.getOperand(0);
3311 EVT InVT = In.getValueType();
3312 EVT ResVT = Op.getValueType();
3313
3314 // Convert loads directly. This is normally done by DAGCombiner,
3315 // but we need this case for bitcasts that are created during lowering
3316 // and which are then lowered themselves.
3317 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
3318 if (ISD::isNormalLoad(LoadN)) {
3319 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
3320 LoadN->getBasePtr(), LoadN->getMemOperand());
3321 // Update the chain uses.
3322 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
3323 return NewLoad;
3324 }
3325
3326 if (InVT == MVT::i32 && ResVT == MVT::f32) {
3327 SDValue In64;
3328 if (Subtarget.hasHighWord()) {
3329 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
3330 MVT::i64);
3331 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3332 MVT::i64, SDValue(U64, 0), In);
3333 } else {
3334 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
3335 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
3336 DAG.getConstant(32, DL, MVT::i64));
3337 }
3338 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
3339 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
3340 DL, MVT::f32, Out64);
3341 }
3342 if (InVT == MVT::f32 && ResVT == MVT::i32) {
3343 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
3344 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3345 MVT::f64, SDValue(U64, 0), In);
3346 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
3347 if (Subtarget.hasHighWord())
3348 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
3349 MVT::i32, Out64);
3350 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
3351 DAG.getConstant(32, DL, MVT::i64));
3352 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
3353 }
3354 llvm_unreachable("Unexpected bitcast combination");
3355}
3356
3357SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
3358 SelectionDAG &DAG) const {
3359 MachineFunction &MF = DAG.getMachineFunction();
3360 SystemZMachineFunctionInfo *FuncInfo =
3361 MF.getInfo<SystemZMachineFunctionInfo>();
3362 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3363
3364 SDValue Chain = Op.getOperand(0);
3365 SDValue Addr = Op.getOperand(1);
3366 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3367 SDLoc DL(Op);
3368
3369 // The initial values of each field.
3370 const unsigned NumFields = 4;
3371 SDValue Fields[NumFields] = {
3372 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
3373 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
3374 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
3375 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
3376 };
3377
3378 // Store each field into its respective slot.
3379 SDValue MemOps[NumFields];
3380 unsigned Offset = 0;
3381 for (unsigned I = 0; I < NumFields; ++I) {
3382 SDValue FieldAddr = Addr;
3383 if (Offset != 0)
3384 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
3385 DAG.getIntPtrConstant(Offset, DL));
3386 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
3387 MachinePointerInfo(SV, Offset));
3388 Offset += 8;
3389 }
3390 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3391}
3392
3393SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
3394 SelectionDAG &DAG) const {
3395 SDValue Chain = Op.getOperand(0);
3396 SDValue DstPtr = Op.getOperand(1);
3397 SDValue SrcPtr = Op.getOperand(2);
3398 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3399 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3400 SDLoc DL(Op);
3401
3402 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
3403 Align(8), /*isVolatile*/ false, /*AlwaysInline*/ false,
3404 /*isTailCall*/ false, MachinePointerInfo(DstSV),
3405 MachinePointerInfo(SrcSV));
3406}
3407
3408SDValue SystemZTargetLowering::
3409lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
3410 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
3411 MachineFunction &MF = DAG.getMachineFunction();
3412 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
3413 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
3414
3415 SDValue Chain = Op.getOperand(0);
3416 SDValue Size = Op.getOperand(1);
3417 SDValue Align = Op.getOperand(2);
3418 SDLoc DL(Op);
3419
3420 // If user has set the no alignment function attribute, ignore
3421 // alloca alignments.
3422 uint64_t AlignVal =
3423 (RealignOpt ? cast<ConstantSDNode>(Align)->getZExtValue() : 0);
3424
3425 uint64_t StackAlign = TFI->getStackAlignment();
3426 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
3427 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
3428
3429 Register SPReg = getStackPointerRegisterToSaveRestore();
3430 SDValue NeededSpace = Size;
3431
3432 // Get a reference to the stack pointer.
3433 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
3434
3435 // If we need a backchain, save it now.
3436 SDValue Backchain;
3437 if (StoreBackchain)
3438 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
3439 MachinePointerInfo());
3440
3441 // Add extra space for alignment if needed.
3442 if (ExtraAlignSpace)
3443 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
3444 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3445
3446 // Get the new stack pointer value.
3447 SDValue NewSP;
3448 if (hasInlineStackProbe(MF)) {
3449 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
3450 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
3451 Chain = NewSP.getValue(1);
3452 }
3453 else {
3454 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
3455 // Copy the new stack pointer back.
3456 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
3457 }
3458
3459 // The allocated data lives above the 160 bytes allocated for the standard
3460 // frame, plus any outgoing stack arguments. We don't know how much that
3461 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
3462 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3463 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
3464
3465 // Dynamically realign if needed.
3466 if (RequiredAlign > StackAlign) {
3467 Result =
3468 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
3469 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3470 Result =
3471 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
3472 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
3473 }
3474
3475 if (StoreBackchain)
3476 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
3477 MachinePointerInfo());
3478
3479 SDValue Ops[2] = { Result, Chain };
3480 return DAG.getMergeValues(Ops, DL);
3481}
3482
3483SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
3484 SDValue Op, SelectionDAG &DAG) const {
3485 SDLoc DL(Op);
3486
3487 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3488}
3489
3490SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
3491 SelectionDAG &DAG) const {
3492 EVT VT = Op.getValueType();
3493 SDLoc DL(Op);
3494 SDValue Ops[2];
3495 if (is32Bit(VT))
3496 // Just do a normal 64-bit multiplication and extract the results.
3497 // We define this so that it can be used for constant division.
3498 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
3499 Op.getOperand(1), Ops[1], Ops[0]);
3500 else if (Subtarget.hasMiscellaneousExtensions2())
3501 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
3502 // the high result in the even register. ISD::SMUL_LOHI is defined to
3503 // return the low half first, so the results are in reverse order.
3504 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
3505 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3506 else {
3507 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
3508 //
3509 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
3510 //
3511 // but using the fact that the upper halves are either all zeros
3512 // or all ones:
3513 //
3514 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
3515 //
3516 // and grouping the right terms together since they are quicker than the
3517 // multiplication:
3518 //
3519 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
3520 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
3521 SDValue LL = Op.getOperand(0);
3522 SDValue RL = Op.getOperand(1);
3523 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
3524 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
3525 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3526 // the high result in the even register. ISD::SMUL_LOHI is defined to
3527 // return the low half first, so the results are in reverse order.
3528 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
3529 LL, RL, Ops[1], Ops[0]);
3530 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
3531 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
3532 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
3533 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
3534 }
3535 return DAG.getMergeValues(Ops, DL);
3536}
3537
3538SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
3539 SelectionDAG &DAG) const {
3540 EVT VT = Op.getValueType();
3541 SDLoc DL(Op);
3542 SDValue Ops[2];
3543 if (is32Bit(VT))
3544 // Just do a normal 64-bit multiplication and extract the results.
3545 // We define this so that it can be used for constant division.
3546 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
3547 Op.getOperand(1), Ops[1], Ops[0]);
3548 else
3549 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3550 // the high result in the even register. ISD::UMUL_LOHI is defined to
3551 // return the low half first, so the results are in reverse order.
3552 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
3553 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3554 return DAG.getMergeValues(Ops, DL);
3555}
3556
3557SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3558 SelectionDAG &DAG) const {
3559 SDValue Op0 = Op.getOperand(0);
3560 SDValue Op1 = Op.getOperand(1);
3561 EVT VT = Op.getValueType();
3562 SDLoc DL(Op);
3563
3564 // We use DSGF for 32-bit division. This means the first operand must
3565 // always be 64-bit, and the second operand should be 32-bit whenever
3566 // that is possible, to improve performance.
3567 if (is32Bit(VT))
3568 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3569 else if (DAG.ComputeNumSignBits(Op1) > 32)
3570 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3571
3572 // DSG(F) returns the remainder in the even register and the
3573 // quotient in the odd register.
3574 SDValue Ops[2];
3575 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
3576 return DAG.getMergeValues(Ops, DL);
3577}
3578
3579SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3580 SelectionDAG &DAG) const {
3581 EVT VT = Op.getValueType();
3582 SDLoc DL(Op);
3583
3584 // DL(G) returns the remainder in the even register and the
3585 // quotient in the odd register.
3586 SDValue Ops[2];
3587 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
3588 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3589 return DAG.getMergeValues(Ops, DL);
3590}
3591
3592SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3593 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3594
3595 // Get the known-zero masks for each operand.
3596 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
3597 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
3598 DAG.computeKnownBits(Ops[1])};
3599
3600 // See if the upper 32 bits of one operand and the lower 32 bits of the
3601 // other are known zero. They are the low and high operands respectively.
3602 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
3603 Known[1].Zero.getZExtValue() };
3604 unsigned High, Low;
3605 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3606 High = 1, Low = 0;
3607 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3608 High = 0, Low = 1;
3609 else
3610 return Op;
3611
3612 SDValue LowOp = Ops[Low];
3613 SDValue HighOp = Ops[High];
3614
3615 // If the high part is a constant, we're better off using IILH.
3616 if (HighOp.getOpcode() == ISD::Constant)
3617 return Op;
3618
3619 // If the low part is a constant that is outside the range of LHI,
3620 // then we're better off using IILF.
3621 if (LowOp.getOpcode() == ISD::Constant) {
3622 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3623 if (!isInt<16>(Value))
3624 return Op;
3625 }
3626
3627 // Check whether the high part is an AND that doesn't change the
3628 // high 32 bits and just masks out low bits. We can skip it if so.
3629 if (HighOp.getOpcode() == ISD::AND &&
3630 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3631 SDValue HighOp0 = HighOp.getOperand(0);
3632 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3633 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3634 HighOp = HighOp0;
3635 }
3636
3637 // Take advantage of the fact that all GR32 operations only change the
3638 // low 32 bits by truncating Low to an i32 and inserting it directly
3639 // using a subreg. The interesting cases are those where the truncation
3640 // can be folded.
3641 SDLoc DL(Op);
3642 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3643 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3644 MVT::i64, HighOp, Low32);
3645}
3646
3647// Lower SADDO/SSUBO/UADDO/USUBO nodes.
3648SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
3649 SelectionDAG &DAG) const {
3650 SDNode *N = Op.getNode();
3651 SDValue LHS = N->getOperand(0);
3652 SDValue RHS = N->getOperand(1);
3653 SDLoc DL(N);
3654 unsigned BaseOp = 0;
3655 unsigned CCValid = 0;
3656 unsigned CCMask = 0;
3657
3658 switch (Op.getOpcode()) {
3659 default: llvm_unreachable("Unknown instruction!");
3660 case ISD::SADDO:
3661 BaseOp = SystemZISD::SADDO;
3662 CCValid = SystemZ::CCMASK_ARITH;
3663 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
3664 break;
3665 case ISD::SSUBO:
3666 BaseOp = SystemZISD::SSUBO;
3667 CCValid = SystemZ::CCMASK_ARITH;
3668 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
3669 break;
3670 case ISD::UADDO:
3671 BaseOp = SystemZISD::UADDO;
3672 CCValid = SystemZ::CCMASK_LOGICAL;
3673 CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
3674 break;
3675 case ISD::USUBO:
3676 BaseOp = SystemZISD::USUBO;
3677 CCValid = SystemZ::CCMASK_LOGICAL;
3678 CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
3679 break;
3680 }
3681
3682 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
3683 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
3684
3685 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
3686 if (N->getValueType(1) == MVT::i1)
3687 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
3688
3689 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
3690}
3691
3692static bool isAddCarryChain(SDValue Carry) {
3693 while (Carry.getOpcode() == ISD::ADDCARRY)
3694 Carry = Carry.getOperand(2);
3695 return Carry.getOpcode() == ISD::UADDO;
3696}
3697
3698static bool isSubBorrowChain(SDValue Carry) {
3699 while (Carry.getOpcode() == ISD::SUBCARRY)
3700 Carry = Carry.getOperand(2);
3701 return Carry.getOpcode() == ISD::USUBO;
3702}
3703
3704// Lower ADDCARRY/SUBCARRY nodes.
3705SDValue SystemZTargetLowering::lowerADDSUBCARRY(SDValue Op,
3706 SelectionDAG &DAG) const {
3707
3708 SDNode *N = Op.getNode();
3709 MVT VT = N->getSimpleValueType(0);
3710
3711 // Let legalize expand this if it isn't a legal type yet.
3712 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3713 return SDValue();
3714
3715 SDValue LHS = N->getOperand(0);
3716 SDValue RHS = N->getOperand(1);
3717 SDValue Carry = Op.getOperand(2);
3718 SDLoc DL(N);
3719 unsigned BaseOp = 0;
3720 unsigned CCValid = 0;
3721 unsigned CCMask = 0;
3722
3723 switch (Op.getOpcode()) {
3724 default: llvm_unreachable("Unknown instruction!");
3725 case ISD::ADDCARRY:
3726 if (!isAddCarryChain(Carry))
3727 return SDValue();
3728
3729 BaseOp = SystemZISD::ADDCARRY;
3730 CCValid = SystemZ::CCMASK_LOGICAL;
3731 CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
3732 break;
3733 case ISD::SUBCARRY:
3734 if (!isSubBorrowChain(Carry))
3735 return SDValue();
3736
3737 BaseOp = SystemZISD::SUBCARRY;
3738 CCValid = SystemZ::CCMASK_LOGICAL;
3739 CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
3740 break;
3741 }
3742
3743 // Set the condition code from the carry flag.
3744 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
3745 DAG.getConstant(CCValid, DL, MVT::i32),
3746 DAG.getConstant(CCMask, DL, MVT::i32));
3747
3748 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3749 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
3750
3751 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
3752 if (N->getValueType(1) == MVT::i1)
3753 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
3754
3755 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
3756}
3757
3758SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3759 SelectionDAG &DAG) const {
3760 EVT VT = Op.getValueType();
3761 SDLoc DL(Op);
3762 Op = Op.getOperand(0);
3763
3764 // Handle vector types via VPOPCT.
3765 if (VT.isVector()) {
3766 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3767 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3768 switch (VT.getScalarSizeInBits()) {
3769 case 8:
3770 break;
3771 case 16: {
3772 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3773 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3774 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3775 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3776 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3777 break;
3778 }
3779 case 32: {
3780 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
3781 DAG.getConstant(0, DL, MVT::i32));
3782 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3783 break;
3784 }
3785 case 64: {
3786 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
3787 DAG.getConstant(0, DL, MVT::i32));
3788 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3789 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3790 break;
3791 }
3792 default:
3793 llvm_unreachable("Unexpected type");
3794 }
3795 return Op;
3796 }
3797
3798 // Get the known-zero mask for the operand.
3799 KnownBits Known = DAG.computeKnownBits(Op);
3800 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
3801 if (NumSignificantBits == 0)
3802 return DAG.getConstant(0, DL, VT);
3803
3804 // Skip known-zero high parts of the operand.
3805 int64_t OrigBitSize = VT.getSizeInBits();
3806 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3807 BitSize = std::min(BitSize, OrigBitSize);
3808
3809 // The POPCNT instruction counts the number of bits in each byte.
3810 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3811 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3812 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3813
3814 // Add up per-byte counts in a binary tree. All bits of Op at
3815 // position larger than BitSize remain zero throughout.
3816 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3817 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3818 if (BitSize != OrigBitSize)
3819 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3820 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3821 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3822 }
3823
3824 // Extract overall result from high byte.
3825 if (BitSize > 8)
3826 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3827 DAG.getConstant(BitSize - 8, DL, VT));
3828
3829 return Op;
3830}
3831
3832SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3833 SelectionDAG &DAG) const {
3834 SDLoc DL(Op);
3835 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3836 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3837 SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
3838 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3839
3840 // The only fence that needs an instruction is a sequentially-consistent
3841 // cross-thread fence.
3842 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3843 FenceSSID == SyncScope::System) {
3844 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3845 Op.getOperand(0)),
3846 0);
3847 }
3848
3849 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3850 return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3851}
3852
3853// Op is an atomic load. Lower it into a normal volatile load.
3854SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3855 SelectionDAG &DAG) const {
3856 auto *Node = cast<AtomicSDNode>(Op.getNode());
3857 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3858 Node->getChain(), Node->getBasePtr(),
3859 Node->getMemoryVT(), Node->getMemOperand());
3860}
3861
3862// Op is an atomic store. Lower it into a normal volatile store.
3863SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3864 SelectionDAG &DAG) const {
3865 auto *Node = cast<AtomicSDNode>(Op.getNode());
3866 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3867 Node->getBasePtr(), Node->getMemoryVT(),
3868 Node->getMemOperand());
3869 // We have to enforce sequential consistency by performing a
3870 // serialization operation after the store.
3871 if (Node->getOrdering() == AtomicOrdering::SequentiallyConsistent)
3872 Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op),
3873 MVT::Other, Chain), 0);
3874 return Chain;
3875}
3876
3877// Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3878// two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3879SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3880 SelectionDAG &DAG,
3881 unsigned Opcode) const {
3882 auto *Node = cast<AtomicSDNode>(Op.getNode());
3883
3884 // 32-bit operations need no code outside the main loop.
3885 EVT NarrowVT = Node->getMemoryVT();
3886 EVT WideVT = MVT::i32;
3887 if (NarrowVT == WideVT)
3888 return Op;
3889
3890 int64_t BitSize = NarrowVT.getSizeInBits();
3891 SDValue ChainIn = Node->getChain();
3892 SDValue Addr = Node->getBasePtr();
3893 SDValue Src2 = Node->getVal();
3894 MachineMemOperand *MMO = Node->getMemOperand();
3895 SDLoc DL(Node);
3896 EVT PtrVT = Addr.getValueType();
3897
3898 // Convert atomic subtracts of constants into additions.
3899 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3900 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3901 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3902 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3903 }
3904
3905 // Get the address of the containing word.
3906 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3907 DAG.getConstant(-4, DL, PtrVT));
3908
3909 // Get the number of bits that the word must be rotated left in order
3910 // to bring the field to the top bits of a GR32.
3911 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3912 DAG.getConstant(3, DL, PtrVT));
3913 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3914
3915 // Get the complementing shift amount, for rotating a field in the top
3916 // bits back to its proper position.
3917 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3918 DAG.getConstant(0, DL, WideVT), BitShift);
3919
3920 // Extend the source operand to 32 bits and prepare it for the inner loop.
3921 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3922 // operations require the source to be shifted in advance. (This shift
3923 // can be folded if the source is constant.) For AND and NAND, the lower
3924 // bits must be set, while for other opcodes they should be left clear.
3925 if (Opcode != SystemZISD::ATOMIC_SWAPW)
3926 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3927 DAG.getConstant(32 - BitSize, DL, WideVT));
3928 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3929 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3930 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3931 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3932
3933 // Construct the ATOMIC_LOADW_* node.
3934 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3935 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3936 DAG.getConstant(BitSize, DL, WideVT) };
3937 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3938 NarrowVT, MMO);
3939
3940 // Rotate the result of the final CS so that the field is in the lower
3941 // bits of a GR32, then truncate it.
3942 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3943 DAG.getConstant(BitSize, DL, WideVT));
3944 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3945
3946 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3947 return DAG.getMergeValues(RetOps, DL);
3948}
3949
3950// Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3951// into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3952// operations into additions.
3953SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3954 SelectionDAG &DAG) const {
3955 auto *Node = cast<AtomicSDNode>(Op.getNode());
3956 EVT MemVT = Node->getMemoryVT();
3957 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3958 // A full-width operation.
3959 assert(Op.getValueType() == MemVT && "Mismatched VTs");
3960 SDValue Src2 = Node->getVal();
3961 SDValue NegSrc2;
3962 SDLoc DL(Src2);
3963
3964 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3965 // Use an addition if the operand is constant and either LAA(G) is
3966 // available or the negative value is in the range of A(G)FHI.
3967 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3968 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3969 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3970 } else if (Subtarget.hasInterlockedAccess1())
3971 // Use LAA(G) if available.
3972 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3973 Src2);
3974
3975 if (NegSrc2.getNode())
3976 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3977 Node->getChain(), Node->getBasePtr(), NegSrc2,
3978 Node->getMemOperand());
3979
3980 // Use the node as-is.
3981 return Op;
3982 }
3983
3984 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3985}
3986
3987// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
3988SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3989 SelectionDAG &DAG) const {
3990 auto *Node = cast<AtomicSDNode>(Op.getNode());
3991 SDValue ChainIn = Node->getOperand(0);
3992 SDValue Addr = Node->getOperand(1);
3993 SDValue CmpVal = Node->getOperand(2);
3994 SDValue SwapVal = Node->getOperand(3);
3995 MachineMemOperand *MMO = Node->getMemOperand();
3996 SDLoc DL(Node);
3997
3998 // We have native support for 32-bit and 64-bit compare and swap, but we
3999 // still need to expand extracting the "success" result from the CC.
4000 EVT NarrowVT = Node->getMemoryVT();
4001 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
4002 if (NarrowVT == WideVT) {
4003 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
4004 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
4005 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
4006 DL, Tys, Ops, NarrowVT, MMO);
4007 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
4008 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
4009
4010 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
4011 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
4012 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
4013 return SDValue();
4014 }
4015
4016 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
4017 // via a fullword ATOMIC_CMP_SWAPW operation.
4018 int64_t BitSize = NarrowVT.getSizeInBits();
4019 EVT PtrVT = Addr.getValueType();
4020
4021 // Get the address of the containing word.
4022 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
4023 DAG.getConstant(-4, DL, PtrVT));
4024
4025 // Get the number of bits that the word must be rotated left in order
4026 // to bring the field to the top bits of a GR32.
4027 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
4028 DAG.getConstant(3, DL, PtrVT));
4029 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
4030
4031 // Get the complementing shift amount, for rotating a field in the top
4032 // bits back to its proper position.
4033 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
4034 DAG.getConstant(0, DL, WideVT), BitShift);
4035
4036 // Construct the ATOMIC_CMP_SWAPW node.
4037 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
4038 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
4039 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
4040 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
4041 VTList, Ops, NarrowVT, MMO);
4042 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
4043 SystemZ::CCMASK_ICMP, SystemZ::CCMASK_CMP_EQ);
4044
4045 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
4046 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
4047 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
4048 return SDValue();
4049}
4050
4051MachineMemOperand::Flags
4052SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
4053 // Because of how we convert atomic_load and atomic_store to normal loads and
4054 // stores in the DAG, we need to ensure that the MMOs are marked volatile
4055 // since DAGCombine hasn't been updated to account for atomic, but non
4056 // volatile loads. (See D57601)
4057 if (auto *SI = dyn_cast<StoreInst>(&I))
4058 if (SI->isAtomic())
4059 return MachineMemOperand::MOVolatile;
4060 if (auto *LI = dyn_cast<LoadInst>(&I))
4061 if (LI->isAtomic())
4062 return MachineMemOperand::MOVolatile;
4063 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
4064 if (AI->isAtomic())
4065 return MachineMemOperand::MOVolatile;
4066 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
4067 if (AI->isAtomic())
4068 return MachineMemOperand::MOVolatile;
4069 return MachineMemOperand::MONone;
4070}
4071
4072SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
4073 SelectionDAG &DAG) const {
4074 MachineFunction &MF = DAG.getMachineFunction();
4075 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
4076 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
4077 report_fatal_error("Variable-sized stack allocations are not supported "
4078 "in GHC calling convention");
4079 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
4080 SystemZ::R15D, Op.getValueType());
4081}
4082
4083SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
4084 SelectionDAG &DAG) const {
4085 MachineFunction &MF = DAG.getMachineFunction();
4086 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
4087 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
4088
4089 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
4090 report_fatal_error("Variable-sized stack allocations are not supported "
4091 "in GHC calling convention");
4092
4093 SDValue Chain = Op.getOperand(0);
4094 SDValue NewSP = Op.getOperand(1);
4095 SDValue Backchain;
4096 SDLoc DL(Op);
4097
4098 if (StoreBackchain) {
4099 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
4100 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4101 MachinePointerInfo());
4102 }
4103
4104 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
4105
4106 if (StoreBackchain)
4107 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4108 MachinePointerInfo());
4109
4110 return Chain;
4111}
4112
4113SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
4114 SelectionDAG &DAG) const {
4115 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4116 if (!IsData)
4117 // Just preserve the chain.
4118 return Op.getOperand(0);
4119
4120 SDLoc DL(Op);
4121 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
4122 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
4123 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
4124 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
4125 Op.getOperand(1)};
4126 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
4127 Node->getVTList(), Ops,
4128 Node->getMemoryVT(), Node->getMemOperand());
4129}
4130
4131// Convert condition code in CCReg to an i32 value.
4132static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg) {
4133 SDLoc DL(CCReg);
4134 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
4135 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
4136 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
4137}
4138
4139SDValue
4140SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
4141 SelectionDAG &DAG) const {
4142 unsigned Opcode, CCValid;
4143 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
4144 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
4145 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
4146 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
4147 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
4148 return SDValue();
4149 }
4150
4151 return SDValue();
4152}
4153
4154SDValue
4155SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
4156 SelectionDAG &DAG) const {
4157 unsigned Opcode, CCValid;
4158 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
4159 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
4160 if (Op->getNumValues() == 1)
4161 return getCCResult(DAG, SDValue(Node, 0));
4162 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
4163 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
4164 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
4165 }
4166
4167 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4168 switch (Id) {
4169 case Intrinsic::thread_pointer:
4170 return lowerThreadPointer(SDLoc(Op), DAG);
4171
4172 case Intrinsic::s390_vpdi:
4173 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
4174 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4175
4176 case Intrinsic::s390_vperm:
4177 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
4178 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4179
4180 case Intrinsic::s390_vuphb:
4181 case Intrinsic::s390_vuphh:
4182 case Intrinsic::s390_vuphf:
4183 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
4184 Op.getOperand(1));
4185
4186 case Intrinsic::s390_vuplhb:
4187 case Intrinsic::s390_vuplhh:
4188 case Intrinsic::s390_vuplhf:
4189 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
4190 Op.getOperand(1));
4191
4192 case Intrinsic::s390_vuplb:
4193 case Intrinsic::s390_vuplhw:
4194 case Intrinsic::s390_vuplf:
4195 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
4196 Op.getOperand(1));
4197
4198 case Intrinsic::s390_vupllb:
4199 case Intrinsic::s390_vupllh:
4200 case Intrinsic::s390_vupllf:
4201 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
4202 Op.getOperand(1));
4203
4204 case Intrinsic::s390_vsumb:
4205 case Intrinsic::s390_vsumh:
4206 case Intrinsic::s390_vsumgh:
4207 case Intrinsic::s390_vsumgf:
4208 case Intrinsic::s390_vsumqf:
4209 case Intrinsic::s390_vsumqg:
4210 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
4211 Op.getOperand(1), Op.getOperand(2));
4212 }
4213
4214 return SDValue();
4215}
4216
4217namespace {
4218// Says that SystemZISD operation Opcode can be used to perform the equivalent
4219// of a VPERM with permute vector Bytes. If Opcode takes three operands,
4220// Operand is the constant third operand, otherwise it is the number of
4221// bytes in each element of the result.
4222struct Permute {
4223 unsigned Opcode;
4224 unsigned Operand;
4225 unsigned char Bytes[SystemZ::VectorBytes];
4226};
4227}
4228
4229static const Permute PermuteForms[] = {
4230 // VMRHG
4231 { SystemZISD::MERGE_HIGH, 8,
4232 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
4233 // VMRHF
4234 { SystemZISD::MERGE_HIGH, 4,
4235 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
4236 // VMRHH
4237 { SystemZISD::MERGE_HIGH, 2,
4238 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
4239 // VMRHB
4240 { SystemZISD::MERGE_HIGH, 1,
4241 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
4242 // VMRLG
4243 { SystemZISD::MERGE_LOW, 8,
4244 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
4245 // VMRLF
4246 { SystemZISD::MERGE_LOW, 4,
4247 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
4248 // VMRLH
4249 { SystemZISD::MERGE_LOW, 2,
4250 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
4251 // VMRLB
4252 { SystemZISD::MERGE_LOW, 1,
4253 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
4254 // VPKG
4255 { SystemZISD::PACK, 4,
4256 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
4257 // VPKF
4258 { SystemZISD::PACK, 2,
4259 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
4260 // VPKH
4261 { SystemZISD::PACK, 1,
4262 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
4263 // VPDI V1, V2, 4 (low half of V1, high half of V2)
4264 { SystemZISD::PERMUTE_DWORDS, 4,
4265 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
4266 // VPDI V1, V2, 1 (high half of V1, low half of V2)
4267 { SystemZISD::PERMUTE_DWORDS, 1,
4268 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
4269};
4270
4271// Called after matching a vector shuffle against a particular pattern.
4272// Both the original shuffle and the pattern have two vector operands.
4273// OpNos[0] is the operand of the original shuffle that should be used for
4274// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
4275// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
4276// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
4277// for operands 0 and 1 of the pattern.
4278static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
4279 if (OpNos[0] < 0) {
4280 if (OpNos[1] < 0)
4281 return false;
4282 OpNo0 = OpNo1 = OpNos[1];
4283 } else if (OpNos[1] < 0) {
4284 OpNo0 = OpNo1 = OpNos[0];
4285 } else {
4286 OpNo0 = OpNos[0];
4287 OpNo1 = OpNos[1];
4288 }
4289 return true;
4290}
4291
4292// Bytes is a VPERM-like permute vector, except that -1 is used for
4293// undefined bytes. Return true if the VPERM can be implemented using P.
4294// When returning true set OpNo0 to the VPERM operand that should be
4295// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
4296//
4297// For example, if swapping the VPERM operands allows P to match, OpNo0
4298// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
4299// operand, but rewriting it to use two duplicated operands allows it to
4300// match P, then OpNo0 and OpNo1 will be the same.
4301static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
4302 unsigned &OpNo0, unsigned &OpNo1) {
4303 int OpNos[] = { -1, -1 };
4304 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
4305 int Elt = Bytes[I];
4306 if (Elt >= 0) {
4307 // Make sure that the two permute vectors use the same suboperand
4308 // byte number. Only the operand numbers (the high bits) are
4309 // allowed to differ.
4310 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
4311 return false;
4312 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
4313 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
4314 // Make sure that the operand mappings are consistent with previous
4315 // elements.
4316 if (OpNos[ModelOpNo] == 1 - RealOpNo)
4317 return false;
4318 OpNos[ModelOpNo] = RealOpNo;
4319 }
4320 }
4321 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
4322}
4323
4324// As above, but search for a matching permute.
4325static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
4326 unsigned &OpNo0, unsigned &OpNo1) {
4327 for (auto &P : PermuteForms)
4328 if (matchPermute(Bytes, P, OpNo0, OpNo1))
4329 return &P;
4330 return nullptr;
4331}
4332
4333// Bytes is a VPERM-like permute vector, except that -1 is used for
4334// undefined bytes. This permute is an operand of an outer permute.
4335// See whether redistributing the -1 bytes gives a shuffle that can be
4336// implemented using P. If so, set Transform to a VPERM-like permute vector
4337// that, when applied to the result of P, gives the original permute in Bytes.
4338static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
4339 const Permute &P,
4340 SmallVectorImpl<int> &Transform) {
4341 unsigned To = 0;
4342 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
4343 int Elt = Bytes[From];
4344 if (Elt < 0)
4345 // Byte number From of the result is undefined.
4346 Transform[From] = -1;
4347 else {
4348 while (P.Bytes[To] != Elt) {
4349 To += 1;
4350 if (To == SystemZ::VectorBytes)
4351 return false;
4352 }
4353 Transform[From] = To;
4354 }
4355 }
4356 return true;
4357}
4358
4359// As above, but search for a matching permute.
4360static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
4361 SmallVectorImpl<int> &Transform) {
4362 for (auto &P : PermuteForms)
4363 if (matchDoublePermute(Bytes, P, Transform))
4364 return &P;
4365 return nullptr;
4366}
4367
4368// Convert the mask of the given shuffle op into a byte-level mask,
4369// as if it had type vNi8.
4370static bool getVPermMask(SDValue ShuffleOp,
4371 SmallVectorImpl<int> &Bytes) {
4372 EVT VT = ShuffleOp.getValueType();
4373 unsigned NumElements = VT.getVectorNumElements();
4374 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4375
4376 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
4377 Bytes.resize(NumElements * BytesPerElement, -1);
4378 for (unsigned I = 0; I < NumElements; ++I) {
4379 int Index = VSN->getMaskElt(I);
4380 if (Index >= 0)
4381 for (unsigned J = 0; J < BytesPerElement; ++J)
4382 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
4383 }
4384 return true;
4385 }
4386 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
4387 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
4388 unsigned Index = ShuffleOp.getConstantOperandVal(1);
4389 Bytes.resize(NumElements * BytesPerElement, -1);
4390 for (unsigned I = 0; I < NumElements; ++I)
4391 for (unsigned J = 0; J < BytesPerElement; ++J)
4392 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
4393 return true;
4394 }
4395 return false;
4396}
4397
4398// Bytes is a VPERM-like permute vector, except that -1 is used for
4399// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
4400// the result come from a contiguous sequence of bytes from one input.
4401// Set Base to the selector for the first byte if so.
4402static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
4403 unsigned BytesPerElement, int &Base) {
4404 Base = -1;
4405 for (unsigned I = 0; I < BytesPerElement; ++I) {
4406 if (Bytes[Start + I] >= 0) {
4407 unsigned Elem = Bytes[Start + I];
4408 if (Base < 0) {
4409 Base = Elem - I;
4410 // Make sure the bytes would come from one input operand.
4411 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
4412 return false;
4413 } else if (unsigned(Base) != Elem - I)
4414 return false;
4415 }
4416 }
4417 return true;
4418}
4419
4420// Bytes is a VPERM-like permute vector, except that -1 is used for
4421// undefined bytes. Return true if it can be performed using VSLDB.
4422// When returning true, set StartIndex to the shift amount and OpNo0
4423// and OpNo1 to the VPERM operands that should be used as the first
4424// and second shift operand respectively.
4425static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
4426 unsigned &StartIndex, unsigned &OpNo0,
4427 unsigned &OpNo1) {
4428 int OpNos[] = { -1, -1 };
4429 int Shift = -1;
4430 for (unsigned I = 0; I < 16; ++I) {
4431 int Index = Bytes[I];
4432 if (Index >= 0) {
4433 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
4434 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
4435 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
4436 if (Shift < 0)
4437 Shift = ExpectedShift;
4438 else if (Shift != ExpectedShift)
4439 return false;
4440 // Make sure that the operand mappings are consistent with previous
4441 // elements.
4442 if (OpNos[ModelOpNo] == 1 - RealOpNo)
4443 return false;
4444 OpNos[ModelOpNo] = RealOpNo;
4445 }
4446 }
4447 StartIndex = Shift;
4448 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
4449}
4450
4451// Create a node that performs P on operands Op0 and Op1, casting the
4452// operands to the appropriate type. The type of the result is determined by P.
4453static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
4454 const Permute &P, SDValue Op0, SDValue Op1) {
4455 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
4456 // elements of a PACK are twice as wide as the outputs.
4457 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
4458 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
4459 P.Operand);
4460 // Cast both operands to the appropriate type.
4461 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
4462 SystemZ::VectorBytes / InBytes);
4463 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
4464 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
4465 SDValue Op;
4466 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
4467 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
4468 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
4469 } else if (P.Opcode == SystemZISD::PACK) {
4470 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
4471 SystemZ::VectorBytes / P.Operand);
4472 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
4473 } else {
4474 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
4475 }
4476 return Op;
4477}
4478
4479static bool isZeroVector(SDValue N) {
4480 if (N->getOpcode() == ISD::BITCAST)
4481 N = N->getOperand(0);
4482 if (N->getOpcode() == ISD::SPLAT_VECTOR)
4483 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
4484 return Op->getZExtValue() == 0;
4485 return ISD::isBuildVectorAllZeros(N.getNode());
4486}
4487
4488// Return the index of the zero/undef vector, or UINT32_MAX if not found.
4489static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
4490 for (unsigned I = 0; I < Num ; I++)
4491 if (isZeroVector(Ops[I]))
4492 return I;
4493 return UINT32_MAX;
4494}
4495
4496// Bytes is a VPERM-like permute vector, except that -1 is used for
4497// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
4498// VSLDB or VPERM.
4499static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
4500 SDValue *Ops,
4501 const SmallVectorImpl<int> &Bytes) {
4502 for (unsigned I = 0; I < 2; ++I)
4503 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
4504
4505 // First see whether VSLDB can be used.
4506 unsigned StartIndex, OpNo0, OpNo1;
4507 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
4508 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
4509 Ops[OpNo1],
4510 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
4511
4512 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
4513 // eliminate a zero vector by reusing any zero index in the permute vector.
4514 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
4515 if (ZeroVecIdx != UINT32_MAX) {
4516 bool MaskFirst = true;
4517 int ZeroIdx = -1;
4518 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
4519 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
4520 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
4521 if (OpNo == ZeroVecIdx && I == 0) {
4522 // If the first byte is zero, use mask as first operand.
4523 ZeroIdx = 0;
4524 break;
4525 }
4526 if (OpNo != ZeroVecIdx && Byte == 0) {
4527 // If mask contains a zero, use it by placing that vector first.
4528 ZeroIdx = I + SystemZ::VectorBytes;
4529 MaskFirst = false;
4530 break;
4531 }
4532 }
4533 if (ZeroIdx != -1) {
4534 SDValue IndexNodes[SystemZ::VectorBytes];
4535 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
4536 if (Bytes[I] >= 0) {
4537 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
4538 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
4539 if (OpNo == ZeroVecIdx)
4540 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
4541 else {
4542 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
4543 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
4544 }
4545 } else
4546 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
4547 }
4548 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
4549 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
4550 if (MaskFirst)
4551 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
4552 Mask);
4553 else
4554 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
4555 Mask);
4556 }
4557 }
4558
4559 SDValue IndexNodes[SystemZ::VectorBytes];
4560 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4561 if (Bytes[I] >= 0)
4562 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
4563 else
4564 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
4565 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
4566 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
4567 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
4568}
4569
4570namespace {
4571// Describes a general N-operand vector shuffle.
4572struct GeneralShuffle {
4573 GeneralShuffle(EVT vt) : VT(vt), UnpackFromEltSize(UINT_MAX) {}
4574 void addUndef();
4575 bool add(SDValue, unsigned);
4576 SDValue getNode(SelectionDAG &, const SDLoc &);
4577 void tryPrepareForUnpack();
4578 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
4579 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
4580
4581 // The operands of the shuffle.
4582 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
4583
4584 // Index I is -1 if byte I of the result is undefined. Otherwise the
4585 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
4586 // Bytes[I] / SystemZ::VectorBytes.
4587 SmallVector<int, SystemZ::VectorBytes> Bytes;
4588
4589 // The type of the shuffle result.
4590 EVT VT;
4591
4592 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
4593 unsigned UnpackFromEltSize;
4594};
4595}
4596
4597// Add an extra undefined element to the shuffle.
4598void GeneralShuffle::addUndef() {
4599 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4600 for (unsigned I = 0; I < BytesPerElement; ++I)
4601 Bytes.push_back(-1);
4602}
4603
4604// Add an extra element to the shuffle, taking it from element Elem of Op.
4605// A null Op indicates a vector input whose value will be calculated later;
4606// there is at most one such input per shuffle and it always has the same
4607// type as the result. Aborts and returns false if the source vector elements
4608// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
4609// LLVM they become implicitly extended, but this is rare and not optimized.
4610bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
4611 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4612
4613 // The source vector can have wider elements than the result,
4614 // either through an explicit TRUNCATE or because of type legalization.
4615 // We want the least significant part.
4616 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
4617 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
4618
4619 // Return false if the source elements are smaller than their destination
4620 // elements.
4621 if (FromBytesPerElement < BytesPerElement)
4622 return false;
4623
4624 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
4625 (FromBytesPerElement - BytesPerElement));
4626
4627 // Look through things like shuffles and bitcasts.
4628 while (Op.getNode()) {
4629 if (Op.getOpcode() == ISD::BITCAST)
4630 Op = Op.getOperand(0);
4631 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
4632 // See whether the bytes we need come from a contiguous part of one
4633 // operand.
4634 SmallVector<int, SystemZ::VectorBytes> OpBytes;
4635 if (!getVPermMask(Op, OpBytes))
4636 break;
4637 int NewByte;
4638 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
4639 break;
4640 if (NewByte < 0) {
4641 addUndef();
4642 return true;
4643 }
4644 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
4645 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
4646 } else if (Op.isUndef()) {
4647 addUndef();
4648 return true;
4649 } else
4650 break;
4651 }
4652
4653 // Make sure that the source of the extraction is in Ops.
4654 unsigned OpNo = 0;
4655 for (; OpNo < Ops.size(); ++OpNo)
4656 if (Ops[OpNo] == Op)
4657 break;
4658 if (OpNo == Ops.size())
4659 Ops.push_back(Op);
4660
4661 // Add the element to Bytes.
4662 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
4663 for (unsigned I = 0; I < BytesPerElement; ++I)
4664 Bytes.push_back(Base + I);
4665
4666 return true;
4667}
4668
4669// Return SDNodes for the completed shuffle.
4670SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
4671 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
4672
4673 if (Ops.size() == 0)
4674 return DAG.getUNDEF(VT);
4675
4676 // Use a single unpack if possible as the last operation.
4677 tryPrepareForUnpack();
4678
4679 // Make sure that there are at least two shuffle operands.
4680 if (Ops.size() == 1)
4681 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
4682
4683 // Create a tree of shuffles, deferring root node until after the loop.
4684 // Try to redistribute the undefined elements of non-root nodes so that
4685 // the non-root shuffles match something like a pack or merge, then adjust
4686 // the parent node's permute vector to compensate for the new order.
4687 // Among other things, this copes with vectors like <2 x i16> that were
4688 // padded with undefined elements during type legalization.
4689 //
4690 // In the best case this redistribution will lead to the whole tree
4691 // using packs and merges. It should rarely be a loss in other cases.
4692 unsigned Stride = 1;
4693 for (; Stride * 2 < Ops.size(); Stride *= 2) {
4694 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
4695 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
4696
4697 // Create a mask for just these two operands.
4698 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
4699 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4700 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
4701 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
4702 if (OpNo == I)
4703 NewBytes[J] = Byte;
4704 else if (OpNo == I + Stride)
4705 NewBytes[J] = SystemZ::VectorBytes + Byte;
4706 else
4707 NewBytes[J] = -1;
4708 }
4709 // See if it would be better to reorganize NewMask to avoid using VPERM.
4710 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
4711 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
4712 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
4713 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
4714 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4715 if (NewBytes[J] >= 0) {
4716 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
4717 "Invalid double permute");
4718 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
4719 } else
4720 assert(NewBytesMap[J] < 0 && "Invalid double permute");
4721 }
4722 } else {
4723 // Just use NewBytes on the operands.
4724 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
4725 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
4726 if (NewBytes[J] >= 0)
4727 Bytes[J] = I * SystemZ::VectorBytes + J;
4728 }
4729 }
4730 }
4731
4732 // Now we just have 2 inputs. Put the second operand in Ops[1].
4733 if (Stride > 1) {
4734 Ops[1] = Ops[Stride];
4735 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4736 if (Bytes[I] >= int(SystemZ::VectorBytes))
4737 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
4738 }
4739
4740 // Look for an instruction that can do the permute without resorting
4741 // to VPERM.
4742 unsigned OpNo0, OpNo1;
4743 SDValue Op;
4744 if (unpackWasPrepared() && Ops[1].isUndef())
4745 Op = Ops[0];
4746 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
4747 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
4748 else
4749 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
4750
4751 Op = insertUnpackIfPrepared(DAG, DL, Op);
4752
4753 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4754}
4755
4756#ifndef NDEBUG
4757static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
4758 dbgs() << Msg.c_str() << " { ";
4759 for (unsigned i = 0; i < Bytes.size(); i++)
4760 dbgs() << Bytes[i] << " ";
4761 dbgs() << "}\n";
4762}
4763#endif
4764
4765// If the Bytes vector matches an unpack operation, prepare to do the unpack
4766// after all else by removing the zero vector and the effect of the unpack on
4767// Bytes.
4768void GeneralShuffle::tryPrepareForUnpack() {
4769 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
4770 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
4771 return;
4772
4773 // Only do this if removing the zero vector reduces the depth, otherwise
4774 // the critical path will increase with the final unpack.
4775 if (Ops.size() > 2 &&
4776 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
4777 return;
4778
4779 // Find an unpack that would allow removing the zero vector from Ops.
4780 UnpackFromEltSize = 1;
4781 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
4782 bool MatchUnpack = true;
4783 SmallVector<int, SystemZ::VectorBytes> SrcBytes;
4784 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
4785 unsigned ToEltSize = UnpackFromEltSize * 2;
4786 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
4787 if (!IsZextByte)
4788 SrcBytes.push_back(Bytes[Elt]);
4789 if (Bytes[Elt] != -1) {
4790 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
4791 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
4792 MatchUnpack = false;
4793 break;
4794 }
4795 }
4796 }
4797 if (MatchUnpack) {
4798 if (Ops.size() == 2) {
4799 // Don't use unpack if a single source operand needs rearrangement.
4800 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++)
4801 if (SrcBytes[i] != -1 && SrcBytes[i] % 16 != int(i)) {
4802 UnpackFromEltSize = UINT_MAX;
4803 return;
4804 }
4805 }
4806 break;
4807 }
4808 }
4809 if (UnpackFromEltSize > 4)
4810 return;
4811
4812 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
4813 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
4814 << ".\n";
4815 dumpBytes(Bytes, "Original Bytes vector:"););
4816
4817 // Apply the unpack in reverse to the Bytes array.
4818 unsigned B = 0;
4819 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
4820 Elt += UnpackFromEltSize;
4821 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
4822 Bytes[B] = Bytes[Elt];
4823 }
4824 while (B < SystemZ::VectorBytes)
4825 Bytes[B++] = -1;
4826
4827 // Remove the zero vector from Ops
4828 Ops.erase(&Ops[ZeroVecOpNo]);
4829 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4830 if (Bytes[I] >= 0) {
4831 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
4832 if (OpNo > ZeroVecOpNo)
4833 Bytes[I] -= SystemZ::VectorBytes;
4834 }
4835
4836 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
4837 dbgs() << "\n";);
4838}
4839
4840SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
4841 const SDLoc &DL,
4842 SDValue Op) {
4843 if (!unpackWasPrepared())
4844 return Op;
4845 unsigned InBits = UnpackFromEltSize * 8;
4846 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
4847 SystemZ::VectorBits / InBits);
4848 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
4849 unsigned OutBits = InBits * 2;
4850 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
4851 SystemZ::VectorBits / OutBits);
4852 return DAG.getNode(SystemZISD::UNPACKL_HIGH, DL, OutVT, PackedOp);
4853}
4854
4855// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
4856static bool isScalarToVector(SDValue Op) {
4857 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
4858 if (!Op.getOperand(I).isUndef())
4859 return false;
4860 return true;
4861}
4862
4863// Return a vector of type VT that contains Value in the first element.
4864// The other elements don't matter.
4865static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4866 SDValue Value) {
4867 // If we have a constant, replicate it to all elements and let the
4868 // BUILD_VECTOR lowering take care of it.
4869 if (Value.getOpcode() == ISD::Constant ||
4870 Value.getOpcode() == ISD::ConstantFP) {
4871 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
4872 return DAG.getBuildVector(VT, DL, Ops);
4873 }
4874 if (Value.isUndef())
4875 return DAG.getUNDEF(VT);
4876 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4877}
4878
4879// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
4880// element 1. Used for cases in which replication is cheap.
4881static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4882 SDValue Op0, SDValue Op1) {
4883 if (Op0.isUndef()) {
4884 if (Op1.isUndef())
4885 return DAG.getUNDEF(VT);
4886 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4887 }
4888 if (Op1.isUndef())
4889 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4890 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4891 buildScalarToVector(DAG, DL, VT, Op0),
4892 buildScalarToVector(DAG, DL, VT, Op1));
4893}
4894
4895// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4896// vector for them.
4897static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4898 SDValue Op1) {
4899 if (Op0.isUndef() && Op1.isUndef())
4900 return DAG.getUNDEF(MVT::v2i64);
4901 // If one of the two inputs is undefined then replicate the other one,
4902 // in order to avoid using another register unnecessarily.
4903 if (Op0.isUndef())
4904 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4905 else if (Op1.isUndef())
4906 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4907 else {
4908 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4909 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4910 }
4911 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4912}
4913
4914// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4915// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4916// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
4917// would benefit from this representation and return it if so.
4918static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4919 BuildVectorSDNode *BVN) {
4920 EVT VT = BVN->getValueType(0);
4921 unsigned NumElements = VT.getVectorNumElements();
4922
4923 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4924 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
4925 // need a BUILD_VECTOR, add an additional placeholder operand for that
4926 // BUILD_VECTOR and store its operands in ResidueOps.
4927 GeneralShuffle GS(VT);
4928 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4929 bool FoundOne = false;
4930 for (unsigned I = 0; I < NumElements; ++I) {
4931 SDValue Op = BVN->getOperand(I);
4932 if (Op.getOpcode() == ISD::TRUNCATE)
4933 Op = Op.getOperand(0);
4934 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4935 Op.getOperand(1).getOpcode() == ISD::Constant) {
4936 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4937 if (!GS.add(Op.getOperand(0), Elem))
4938 return SDValue();
4939 FoundOne = true;
4940 } else if (Op.isUndef()) {
4941 GS.addUndef();
4942 } else {
4943 if (!GS.add(SDValue(), ResidueOps.size()))
4944 return SDValue();
4945 ResidueOps.push_back(BVN->getOperand(I));
4946 }
4947 }
4948
4949 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4950 if (!FoundOne)
4951 return SDValue();
4952
4953 // Create the BUILD_VECTOR for the remaining elements, if any.
4954 if (!ResidueOps.empty()) {
4955 while (ResidueOps.size() < NumElements)
4956 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4957 for (auto &Op : GS.Ops) {
4958 if (!Op.getNode()) {
4959 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4960 break;
4961 }
4962 }
4963 }
4964 return GS.getNode(DAG, SDLoc(BVN));
4965}
4966
4967bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
4968 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
4969 return true;
4970 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
4971 return true;
4972 return false;
4973}
4974
4975// Combine GPR scalar values Elems into a vector of type VT.
4976SDValue
4977SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4978 SmallVectorImpl<SDValue> &Elems) const {
4979 // See whether there is a single replicated value.
4980 SDValue Single;
4981 unsigned int NumElements = Elems.size();
4982 unsigned int Count = 0;
4983 for (auto Elem : Elems) {
4984 if (!Elem.isUndef()) {
4985 if (!Single.getNode())
4986 Single = Elem;
4987 else if (Elem != Single) {
4988 Single = SDValue();
4989 break;
4990 }
4991 Count += 1;
4992 }
4993 }
4994 // There are three cases here:
4995 //
4996 // - if the only defined element is a loaded one, the best sequence
4997 // is a replicating load.
4998 //
4999 // - otherwise, if the only defined element is an i64 value, we will
5000 // end up with the same VLVGP sequence regardless of whether we short-cut
5001 // for replication or fall through to the later code.
5002 //
5003 // - otherwise, if the only defined element is an i32 or smaller value,
5004 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
5005 // This is only a win if the single defined element is used more than once.
5006 // In other cases we're better off using a single VLVGx.
5007 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
5008 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
5009
5010 // If all elements are loads, use VLREP/VLEs (below).
5011 bool AllLoads = true;
5012 for (auto Elem : Elems)
5013 if (!isVectorElementLoad(Elem)) {
5014 AllLoads = false;
5015 break;
5016 }
5017
5018 // The best way of building a v2i64 from two i64s is to use VLVGP.
5019 if (VT == MVT::v2i64 && !AllLoads)
5020 return joinDwords(DAG, DL, Elems[0], Elems[1]);
5021
5022 // Use a 64-bit merge high to combine two doubles.
5023 if (VT == MVT::v2f64 && !AllLoads)
5024 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
5025
5026 // Build v4f32 values directly from the FPRs:
5027 //
5028 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
5029 // V V VMRHF
5030 // <ABxx> <CDxx>
5031 // V VMRHG
5032 // <ABCD>
5033 if (VT == MVT::v4f32 && !AllLoads) {
5034 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
5035 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
5036 // Avoid unnecessary undefs by reusing the other operand.
5037 if (Op01.isUndef())
5038 Op01 = Op23;
5039 else if (Op23.isUndef())
5040 Op23 = Op01;
5041 // Merging identical replications is a no-op.
5042 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
5043 return Op01;
5044 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
5045 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
5046 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
5047 DL, MVT::v2i64, Op01, Op23);
5048 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
5049 }
5050
5051 // Collect the constant terms.
5052 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
5053 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
5054
5055 unsigned NumConstants = 0;
5056 for (unsigned I = 0; I < NumElements; ++I) {
5057 SDValue Elem = Elems[I];
5058 if (Elem.getOpcode() == ISD::Constant ||
5059 Elem.getOpcode() == ISD::ConstantFP) {
5060 NumConstants += 1;
5061 Constants[I] = Elem;
5062 Done[I] = true;
5063 }
5064 }
5065 // If there was at least one constant, fill in the other elements of
5066 // Constants with undefs to get a full vector constant and use that
5067 // as the starting point.
5068 SDValue Result;
5069 SDValue ReplicatedVal;
5070 if (NumConstants > 0) {
5071 for (unsigned I = 0; I < NumElements; ++I)
5072 if (!Constants[I].getNode())
5073 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
5074 Result = DAG.getBuildVector(VT, DL, Constants);
5075 } else {
5076 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
5077 // avoid a false dependency on any previous contents of the vector
5078 // register.
5079
5080 // Use a VLREP if at least one element is a load. Make sure to replicate
5081 // the load with the most elements having its value.
5082 std::map<const SDNode*, unsigned> UseCounts;
5083 SDNode *LoadMaxUses = nullptr;
5084 for (unsigned I = 0; I < NumElements; ++I)
5085 if (isVectorElementLoad(Elems[I])) {
5086 SDNode *Ld = Elems[I].getNode();
5087 UseCounts[Ld]++;
5088 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < UseCounts[Ld])
5089 LoadMaxUses = Ld;
5090 }
5091 if (LoadMaxUses != nullptr) {
5092 ReplicatedVal = SDValue(LoadMaxUses, 0);
5093 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
5094 } else {
5095 // Try to use VLVGP.
5096 unsigned I1 = NumElements / 2 - 1;
5097 unsigned I2 = NumElements - 1;
5098 bool Def1 = !Elems[I1].isUndef();
5099 bool Def2 = !Elems[I2].isUndef();
5100 if (Def1 || Def2) {
5101 SDValue Elem1 = Elems[Def1 ? I1 : I2];
5102 SDValue Elem2 = Elems[Def2 ? I2 : I1];
5103 Result = DAG.getNode(ISD::BITCAST, DL, VT,
5104 joinDwords(DAG, DL, Elem1, Elem2));
5105 Done[I1] = true;
5106 Done[I2] = true;
5107 } else
5108 Result = DAG.getUNDEF(VT);
5109 }
5110 }
5111
5112 // Use VLVGx to insert the other elements.
5113 for (unsigned I = 0; I < NumElements; ++I)
5114 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
5115 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
5116 DAG.getConstant(I, DL, MVT::i32));
5117 return Result;
5118}
5119
5120SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
5121 SelectionDAG &DAG) const {
5122 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
5123 SDLoc DL(Op);
5124 EVT VT = Op.getValueType();
5125
5126 if (BVN->isConstant()) {
5127 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
5128 return Op;
5129
5130 // Fall back to loading it from memory.
5131 return SDValue();
5132 }
5133
5134 // See if we should use shuffles to construct the vector from other vectors.
5135 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
5136 return Res;
5137
5138 // Detect SCALAR_TO_VECTOR conversions.
5139 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
5140 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
5141
5142 // Otherwise use buildVector to build the vector up from GPRs.
5143 unsigned NumElements = Op.getNumOperands();
5144 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
5145 for (unsigned I = 0; I < NumElements; ++I)
5146 Ops[I] = Op.getOperand(I);
5147 return buildVector(DAG, DL, VT, Ops);
5148}
5149
5150SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5151 SelectionDAG &DAG) const {
5152 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
5153 SDLoc DL(Op);
5154 EVT VT = Op.getValueType();
5155 unsigned NumElements = VT.getVectorNumElements();
5156
5157 if (VSN->isSplat()) {
5158 SDValue Op0 = Op.getOperand(0);
5159 unsigned Index = VSN->getSplatIndex();
5160 assert(Index < VT.getVectorNumElements() &&
5161 "Splat index should be defined and in first operand");
5162 // See whether the value we're splatting is directly available as a scalar.
5163 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
5164 Op0.getOpcode() == ISD::BUILD_VECTOR)
5165 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
5166 // Otherwise keep it as a vector-to-vector operation.
5167 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
5168 DAG.getTargetConstant(Index, DL, MVT::i32));
5169 }
5170
5171 GeneralShuffle GS(VT);
5172 for (unsigned I = 0; I < NumElements; ++I) {
5173 int Elt = VSN->getMaskElt(I);
5174 if (Elt < 0)
5175 GS.addUndef();
5176 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
5177 unsigned(Elt) % NumElements))
5178 return SDValue();
5179 }
5180 return GS.getNode(DAG, SDLoc(VSN));
5181}
5182
5183SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5184 SelectionDAG &DAG) const {
5185 SDLoc DL(Op);
5186 // Just insert the scalar into element 0 of an undefined vector.
5187 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
5188 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
5189 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
5190}
5191
5192SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5193 SelectionDAG &DAG) const {
5194 // Handle insertions of floating-point values.
5195 SDLoc DL(Op);
5196 SDValue Op0 = Op.getOperand(0);
5197 SDValue Op1 = Op.getOperand(1);
5198 SDValue Op2 = Op.getOperand(2);
5199 EVT VT = Op.getValueType();
5200
5201 // Insertions into constant indices of a v2f64 can be done using VPDI.
5202 // However, if the inserted value is a bitcast or a constant then it's
5203 // better to use GPRs, as below.
5204 if (VT == MVT::v2f64 &&
5205 Op1.getOpcode() != ISD::BITCAST &&
5206 Op1.getOpcode() != ISD::ConstantFP &&
5207 Op2.getOpcode() == ISD::Constant) {
5208 uint64_t Index = cast<ConstantSDNode>(Op2)->getZExtValue();
5209 unsigned Mask = VT.getVectorNumElements() - 1;
5210 if (Index <= Mask)
5211 return Op;
5212 }
5213
5214 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
5215 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
5216 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
5217 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
5218 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
5219 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
5220 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5221}
5222
5223SDValue
5224SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5225 SelectionDAG &DAG) const {
5226 // Handle extractions of floating-point values.
5227 SDLoc DL(Op);
5228 SDValue Op0 = Op.getOperand(0);
5229 SDValue Op1 = Op.getOperand(1);
5230 EVT VT = Op.getValueType();
5231 EVT VecVT = Op0.getValueType();
5232
5233 // Extractions of constant indices can be done directly.
5234 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
5235 uint64_t Index = CIndexN->getZExtValue();
5236 unsigned Mask = VecVT.getVectorNumElements() - 1;
5237 if (Index <= Mask)
5238 return Op;
5239 }
5240
5241 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
5242 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
5243 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
5244 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
5245 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
5246 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5247}
5248
5249SDValue SystemZTargetLowering::
5250lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
5251 SDValue PackedOp = Op.getOperand(0);
5252 EVT OutVT = Op.getValueType();
5253 EVT InVT = PackedOp.getValueType();
5254 unsigned ToBits = OutVT.getScalarSizeInBits();
5255 unsigned FromBits = InVT.getScalarSizeInBits();
5256 do {
5257 FromBits *= 2;
5258 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
5259 SystemZ::VectorBits / FromBits);
5260 PackedOp =
5261 DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(PackedOp), OutVT, PackedOp);
5262 } while (FromBits != ToBits);
5263 return PackedOp;
5264}
5265
5266// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
5267SDValue SystemZTargetLowering::
5268lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
5269 SDValue PackedOp = Op.getOperand(0);
5270 SDLoc DL(Op);
5271 EVT OutVT = Op.getValueType();
5272 EVT InVT = PackedOp.getValueType();
5273 unsigned InNumElts = InVT.getVectorNumElements();
5274 unsigned OutNumElts = OutVT.getVectorNumElements();
5275 unsigned NumInPerOut = InNumElts / OutNumElts;
5276
5277 SDValue ZeroVec =
5278 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
5279
5280 SmallVector<int, 16> Mask(InNumElts);
5281 unsigned ZeroVecElt = InNumElts;
5282 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
5283 unsigned MaskElt = PackedElt * NumInPerOut;
5284 unsigned End = MaskElt + NumInPerOut - 1;
5285 for (; MaskElt < End; MaskElt++)
5286 Mask[MaskElt] = ZeroVecElt++;
5287 Mask[MaskElt] = PackedElt;
5288 }
5289 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
5290 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
5291}
5292
5293SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
5294 unsigned ByScalar) const {
5295 // Look for cases where a vector shift can use the *_BY_SCALAR form.
5296 SDValue Op0 = Op.getOperand(0);
5297 SDValue Op1 = Op.getOperand(1);
5298 SDLoc DL(Op);
5299 EVT VT = Op.getValueType();
5300 unsigned ElemBitSize = VT.getScalarSizeInBits();
5301
5302 // See whether the shift vector is a splat represented as BUILD_VECTOR.
5303 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
5304 APInt SplatBits, SplatUndef;
5305 unsigned SplatBitSize;
5306 bool HasAnyUndefs;
5307 // Check for constant splats. Use ElemBitSize as the minimum element
5308 // width and reject splats that need wider elements.
5309 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5310 ElemBitSize, true) &&
5311 SplatBitSize == ElemBitSize) {
5312 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
5313 DL, MVT::i32);
5314 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5315 }
5316 // Check for variable splats.
5317 BitVector UndefElements;
5318 SDValue Splat = BVN->getSplatValue(&UndefElements);
5319 if (Splat) {
5320 // Since i32 is the smallest legal type, we either need a no-op
5321 // or a truncation.
5322 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
5323 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5324 }
5325 }
5326
5327 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
5328 // and the shift amount is directly available in a GPR.
5329 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
5330 if (VSN->isSplat()) {
5331 SDValue VSNOp0 = VSN->getOperand(0);
5332 unsigned Index = VSN->getSplatIndex();
5333 assert(Index < VT.getVectorNumElements() &&
5334 "Splat index should be defined and in first operand");
5335 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
5336 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
5337 // Since i32 is the smallest legal type, we either need a no-op
5338 // or a truncation.
5339 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
5340 VSNOp0.getOperand(Index));
5341 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5342 }
5343 }
5344 }
5345
5346 // Otherwise just treat the current form as legal.
5347 return Op;
5348}
5349
5350SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
5351 SelectionDAG &DAG) const {
5352 switch (Op.getOpcode()) {
5353 case ISD::FRAMEADDR:
5354 return lowerFRAMEADDR(Op, DAG);
5355 case ISD::RETURNADDR:
5356 return lowerRETURNADDR(Op, DAG);
5357 case ISD::BR_CC:
5358 return lowerBR_CC(Op, DAG);
5359 case ISD::SELECT_CC:
5360 return lowerSELECT_CC(Op, DAG);
5361 case ISD::SETCC:
5362 return lowerSETCC(Op, DAG);
5363 case ISD::STRICT_FSETCC:
5364 return lowerSTRICT_FSETCC(Op, DAG, false);
5365 case ISD::STRICT_FSETCCS:
5366 return lowerSTRICT_FSETCC(Op, DAG, true);
5367 case ISD::GlobalAddress:
5368 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
5369 case ISD::GlobalTLSAddress:
5370 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
5371 case ISD::BlockAddress:
5372 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
5373 case ISD::JumpTable:
5374 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
5375 case ISD::ConstantPool:
5376 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
5377 case ISD::BITCAST:
5378 return lowerBITCAST(Op, DAG);
5379 case ISD::VASTART:
5380 return lowerVASTART(Op, DAG);
5381 case ISD::VACOPY:
5382 return lowerVACOPY(Op, DAG);
5383 case ISD::DYNAMIC_STACKALLOC:
5384 return lowerDYNAMIC_STACKALLOC(Op, DAG);
5385 case ISD::GET_DYNAMIC_AREA_OFFSET:
5386 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
5387 case ISD::SMUL_LOHI:
5388 return lowerSMUL_LOHI(Op, DAG);
5389 case ISD::UMUL_LOHI:
5390 return lowerUMUL_LOHI(Op, DAG);
5391 case ISD::SDIVREM:
5392 return lowerSDIVREM(Op, DAG);
5393 case ISD::UDIVREM:
5394 return lowerUDIVREM(Op, DAG);
5395 case ISD::SADDO:
5396 case ISD::SSUBO:
5397 case ISD::UADDO:
5398 case ISD::USUBO:
5399 return lowerXALUO(Op, DAG);
5400 case ISD::ADDCARRY:
5401 case ISD::SUBCARRY:
5402 return lowerADDSUBCARRY(Op, DAG);
5403 case ISD::OR:
5404 return lowerOR(Op, DAG);
5405 case ISD::CTPOP:
5406 return lowerCTPOP(Op, DAG);
5407 case ISD::ATOMIC_FENCE:
5408 return lowerATOMIC_FENCE(Op, DAG);
5409 case ISD::ATOMIC_SWAP:
5410 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
5411 case ISD::ATOMIC_STORE:
5412 return lowerATOMIC_STORE(Op, DAG);
5413 case ISD::ATOMIC_LOAD:
5414 return lowerATOMIC_LOAD(Op, DAG);
5415 case ISD::ATOMIC_LOAD_ADD:
5416 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
5417 case ISD::ATOMIC_LOAD_SUB:
5418 return lowerATOMIC_LOAD_SUB(Op, DAG);
5419 case ISD::ATOMIC_LOAD_AND:
5420 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
5421 case ISD::ATOMIC_LOAD_OR:
5422 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
5423 case ISD::ATOMIC_LOAD_XOR:
5424 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
5425 case ISD::ATOMIC_LOAD_NAND:
5426 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
5427 case ISD::ATOMIC_LOAD_MIN:
5428 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
5429 case ISD::ATOMIC_LOAD_MAX:
5430 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
5431 case ISD::ATOMIC_LOAD_UMIN:
5432 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
5433 case ISD::ATOMIC_LOAD_UMAX:
5434 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
5435 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
5436 return lowerATOMIC_CMP_SWAP(Op, DAG);
5437 case ISD::STACKSAVE:
5438 return lowerSTACKSAVE(Op, DAG);
5439 case ISD::STACKRESTORE:
5440 return lowerSTACKRESTORE(Op, DAG);
5441 case ISD::PREFETCH:
5442 return lowerPREFETCH(Op, DAG);
5443 case ISD::INTRINSIC_W_CHAIN:
5444 return lowerINTRINSIC_W_CHAIN(Op, DAG);
5445 case ISD::INTRINSIC_WO_CHAIN:
5446 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
5447 case ISD::BUILD_VECTOR:
5448 return lowerBUILD_VECTOR(Op, DAG);
5449 case ISD::VECTOR_SHUFFLE:
5450 return lowerVECTOR_SHUFFLE(Op, DAG);
5451 case ISD::SCALAR_TO_VECTOR:
5452 return lowerSCALAR_TO_VECTOR(Op, DAG);
5453 case ISD::INSERT_VECTOR_ELT:
5454 return lowerINSERT_VECTOR_ELT(Op, DAG);
5455 case ISD::EXTRACT_VECTOR_ELT:
5456 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
5457 case ISD::SIGN_EXTEND_VECTOR_INREG:
5458 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
5459 case ISD::ZERO_EXTEND_VECTOR_INREG:
5460 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
5461 case ISD::SHL:
5462 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
5463 case ISD::SRL:
5464 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
5465 case ISD::SRA:
5466 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
5467 default:
5468 llvm_unreachable("Unexpected node to lower");
5469 }
5470}
5471
5472// Lower operations with invalid operand or result types (currently used
5473// only for 128-bit integer types).
5474
5475static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In) {
5476 SDLoc DL(In);
5477 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
5478 DAG.getIntPtrConstant(0, DL));
5479 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
5480 DAG.getIntPtrConstant(1, DL));
5481 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
5482 MVT::Untyped, Hi, Lo);
5483 return SDValue(Pair, 0);
5484}
5485
5486static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In) {
5487 SDLoc DL(In);
5488 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
5489 DL, MVT::i64, In);
5490 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
5491 DL, MVT::i64, In);
5492 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
5493}
5494
5495void
5496SystemZTargetLowering::LowerOperationWrapper(SDNode *N,
5497 SmallVectorImpl<SDValue> &Results,
5498 SelectionDAG &DAG) const {
5499 switch (N->getOpcode()) {
5500 case ISD::ATOMIC_LOAD: {
5501 SDLoc DL(N);
5502 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other);
5503 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
5504 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5505 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
5506 DL, Tys, Ops, MVT::i128, MMO);
5507 Results.push_back(lowerGR128ToI128(DAG, Res));
5508 Results.push_back(Res.getValue(1));
5509 break;
5510 }
5511 case ISD::ATOMIC_STORE: {
5512 SDLoc DL(N);
5513 SDVTList Tys = DAG.getVTList(MVT::Other);
5514 SDValue Ops[] = { N->getOperand(0),
5515 lowerI128ToGR128(DAG, N->getOperand(2)),
5516 N->getOperand(1) };
5517 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5518 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
5519 DL, Tys, Ops, MVT::i128, MMO);
5520 // We have to enforce sequential consistency by performing a
5521 // serialization operation after the store.
5522 if (cast<AtomicSDNode>(N)->getOrdering() ==
5523 AtomicOrdering::SequentiallyConsistent)
5524 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
5525 MVT::Other, Res), 0);
5526 Results.push_back(Res);
5527 break;
5528 }
5529 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
5530 SDLoc DL(N);
5531 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other);
5532 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
5533 lowerI128ToGR128(DAG, N->getOperand(2)),
5534 lowerI128ToGR128(DAG, N->getOperand(3)) };
5535 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5536 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
5537 DL, Tys, Ops, MVT::i128, MMO);
5538 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
5539 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
5540 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
5541 Results.push_back(lowerGR128ToI128(DAG, Res));
5542 Results.push_back(Success);
5543 Results.push_back(Res.getValue(2));
5544 break;
5545 }
5546 default:
5547 llvm_unreachable("Unexpected node to lower");
5548 }
5549}
5550
5551void
5552SystemZTargetLowering::ReplaceNodeResults(SDNode *N,
5553 SmallVectorImpl<SDValue> &Results,
5554 SelectionDAG &DAG) const {
5555 return LowerOperationWrapper(N, Results, DAG);
5556}
5557
5558const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
5559#define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
5560 switch ((SystemZISD::NodeType)Opcode) {
5561 case SystemZISD::FIRST_NUMBER: break;
5562 OPCODE(RET_FLAG);
5563 OPCODE(CALL);
5564 OPCODE(SIBCALL);
5565 OPCODE(TLS_GDCALL);
5566 OPCODE(TLS_LDCALL);
5567 OPCODE(PCREL_WRAPPER);
5568 OPCODE(PCREL_OFFSET);
5569 OPCODE(ICMP);
5570 OPCODE(FCMP);
5571 OPCODE(STRICT_FCMP);
5572 OPCODE(STRICT_FCMPS);
5573 OPCODE(TM);
5574 OPCODE(BR_CCMASK);
5575 OPCODE(SELECT_CCMASK);
5576 OPCODE(ADJDYNALLOC);
5577 OPCODE(PROBED_ALLOCA);
5578 OPCODE(POPCNT);
5579 OPCODE(SMUL_LOHI);
5580 OPCODE(UMUL_LOHI);
5581 OPCODE(SDIVREM);
5582 OPCODE(UDIVREM);
5583 OPCODE(SADDO);
5584 OPCODE(SSUBO);
5585 OPCODE(UADDO);
5586 OPCODE(USUBO);
5587 OPCODE(ADDCARRY);
5588 OPCODE(SUBCARRY);
5589 OPCODE(GET_CCMASK);
5590 OPCODE(MVC);
5591 OPCODE(MVC_LOOP);
5592 OPCODE(NC);
5593 OPCODE(NC_LOOP);
5594 OPCODE(OC);
5595 OPCODE(OC_LOOP);
5596 OPCODE(XC);
5597 OPCODE(XC_LOOP);
5598 OPCODE(CLC);
5599 OPCODE(CLC_LOOP);
5600 OPCODE(STPCPY);
5601 OPCODE(STRCMP);
5602 OPCODE(SEARCH_STRING);
5603 OPCODE(IPM);
5604 OPCODE(MEMBARRIER);
5605 OPCODE(TBEGIN);
5606 OPCODE(TBEGIN_NOFLOAT);
5607 OPCODE(TEND);
5608 OPCODE(BYTE_MASK);
5609 OPCODE(ROTATE_MASK);
5610 OPCODE(REPLICATE);
5611 OPCODE(JOIN_DWORDS);
5612 OPCODE(SPLAT);
5613 OPCODE(MERGE_HIGH);
5614 OPCODE(MERGE_LOW);
5615 OPCODE(SHL_DOUBLE);
5616 OPCODE(PERMUTE_DWORDS);
5617 OPCODE(PERMUTE);
5618 OPCODE(PACK);
5619 OPCODE(PACKS_CC);
5620 OPCODE(PACKLS_CC);
5621 OPCODE(UNPACK_HIGH);
5622 OPCODE(UNPACKL_HIGH);
5623 OPCODE(UNPACK_LOW);
5624 OPCODE(UNPACKL_LOW);
5625 OPCODE(VSHL_BY_SCALAR);
5626 OPCODE(VSRL_BY_SCALAR);
5627 OPCODE(VSRA_BY_SCALAR);
5628 OPCODE(VSUM);
5629 OPCODE(VICMPE);
5630 OPCODE(VICMPH);
5631 OPCODE(VICMPHL);
5632 OPCODE(VICMPES);
5633 OPCODE(VICMPHS);
5634 OPCODE(VICMPHLS);
5635 OPCODE(VFCMPE);
5636 OPCODE(STRICT_VFCMPE);
5637 OPCODE(STRICT_VFCMPES);
5638 OPCODE(VFCMPH);
5639 OPCODE(STRICT_VFCMPH);
5640 OPCODE(STRICT_VFCMPHS);
5641 OPCODE(VFCMPHE);
5642 OPCODE(STRICT_VFCMPHE);
5643 OPCODE(STRICT_VFCMPHES);
5644 OPCODE(VFCMPES);
5645 OPCODE(VFCMPHS);
5646 OPCODE(VFCMPHES);
5647 OPCODE(VFTCI);
5648 OPCODE(VEXTEND);
5649 OPCODE(STRICT_VEXTEND);
5650 OPCODE(VROUND);
5651 OPCODE(STRICT_VROUND);
5652 OPCODE(VTM);
5653 OPCODE(VFAE_CC);
5654 OPCODE(VFAEZ_CC);
5655 OPCODE(VFEE_CC);
5656 OPCODE(VFEEZ_CC);
5657 OPCODE(VFENE_CC);
5658 OPCODE(VFENEZ_CC);
5659 OPCODE(VISTR_CC);
5660 OPCODE(VSTRC_CC);
5661 OPCODE(VSTRCZ_CC);
5662 OPCODE(VSTRS_CC);
5663 OPCODE(VSTRSZ_CC);
5664 OPCODE(TDC);
5665 OPCODE(ATOMIC_SWAPW);
5666 OPCODE(ATOMIC_LOADW_ADD);
5667 OPCODE(ATOMIC_LOADW_SUB);
5668 OPCODE(ATOMIC_LOADW_AND);
5669 OPCODE(ATOMIC_LOADW_OR);
5670 OPCODE(ATOMIC_LOADW_XOR);
5671 OPCODE(ATOMIC_LOADW_NAND);
5672 OPCODE(ATOMIC_LOADW_MIN);
5673 OPCODE(ATOMIC_LOADW_MAX);
5674 OPCODE(ATOMIC_LOADW_UMIN);
5675 OPCODE(ATOMIC_LOADW_UMAX);
5676 OPCODE(ATOMIC_CMP_SWAPW);
5677 OPCODE(ATOMIC_CMP_SWAP);
5678 OPCODE(ATOMIC_LOAD_128);
5679 OPCODE(ATOMIC_STORE_128);
5680 OPCODE(ATOMIC_CMP_SWAP_128);
5681 OPCODE(LRV);
5682 OPCODE(STRV);
5683 OPCODE(VLER);
5684 OPCODE(VSTER);
5685 OPCODE(PREFETCH);
5686 }
5687 return nullptr;
5688#undef OPCODE
5689}
5690
5691// Return true if VT is a vector whose elements are a whole number of bytes
5692// in width. Also check for presence of vector support.
5693bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
5694 if (!Subtarget.hasVector())
5695 return false;
5696
5697 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
5698}
5699
5700// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
5701// producing a result of type ResVT. Op is a possibly bitcast version
5702// of the input vector and Index is the index (based on type VecVT) that
5703// should be extracted. Return the new extraction if a simplification
5704// was possible or if Force is true.
5705SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
5706 EVT VecVT, SDValue Op,
5707 unsigned Index,
5708 DAGCombinerInfo &DCI,
5709 bool Force) const {
5710 SelectionDAG &DAG = DCI.DAG;
5711
5712 // The number of bytes being extracted.
5713 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
5714
5715 for (;;) {
5716 unsigned Opcode = Op.getOpcode();
5717 if (Opcode == ISD::BITCAST)
5718 // Look through bitcasts.
5719 Op = Op.getOperand(0);
5720 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
5721 canTreatAsByteVector(Op.getValueType())) {
5722 // Get a VPERM-like permute mask and see whether the bytes covered
5723 // by the extracted element are a contiguous sequence from one
5724 // source operand.
5725 SmallVector<int, SystemZ::VectorBytes> Bytes;
5726 if (!getVPermMask(Op, Bytes))
5727 break;
5728 int First;
5729 if (!getShuffleInput(Bytes, Index * BytesPerElement,
5730 BytesPerElement, First))
5731 break;
5732 if (First < 0)
5733 return DAG.getUNDEF(ResVT);
5734 // Make sure the contiguous sequence starts at a multiple of the
5735 // original element size.
5736 unsigned Byte = unsigned(First) % Bytes.size();
5737 if (Byte % BytesPerElement != 0)
5738 break;
5739 // We can get the extracted value directly from an input.
5740 Index = Byte / BytesPerElement;
5741 Op = Op.getOperand(unsigned(First) / Bytes.size());
5742 Force = true;
5743 } else if (Opcode == ISD::BUILD_VECTOR &&
5744 canTreatAsByteVector(Op.getValueType())) {
5745 // We can only optimize this case if the BUILD_VECTOR elements are
5746 // at least as wide as the extracted value.
5747 EVT OpVT = Op.getValueType();
5748 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
5749 if (OpBytesPerElement < BytesPerElement)
5750 break;
5751 // Make sure that the least-significant bit of the extracted value
5752 // is the least significant bit of an input.
5753 unsigned End = (Index + 1) * BytesPerElement;
5754 if (End % OpBytesPerElement != 0)
5755 break;
5756 // We're extracting the low part of one operand of the BUILD_VECTOR.
5757 Op = Op.getOperand(End / OpBytesPerElement - 1);
5758 if (!Op.getValueType().isInteger()) {
5759 EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
5760 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5761 DCI.AddToWorklist(Op.getNode());
5762 }
5763 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
5764 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5765 if (VT != ResVT) {
5766 DCI.AddToWorklist(Op.getNode());
5767 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
5768 }
5769 return Op;
5770 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5771 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
5772 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
5773 canTreatAsByteVector(Op.getValueType()) &&
5774 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
5775 // Make sure that only the unextended bits are significant.
5776 EVT ExtVT = Op.getValueType();
5777 EVT OpVT = Op.getOperand(0).getValueType();
5778 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
5779 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
5780 unsigned Byte = Index * BytesPerElement;
5781 unsigned SubByte = Byte % ExtBytesPerElement;
5782 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
5783 if (SubByte < MinSubByte ||
5784 SubByte + BytesPerElement > ExtBytesPerElement)
5785 break;
5786 // Get the byte offset of the unextended element
5787 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
5788 // ...then add the byte offset relative to that element.
5789 Byte += SubByte - MinSubByte;
5790 if (Byte % BytesPerElement != 0)
5791 break;
5792 Op = Op.getOperand(0);
5793 Index = Byte / BytesPerElement;
5794 Force = true;
5795 } else
5796 break;
5797 }
5798 if (Force) {
5799 if (Op.getValueType() != VecVT) {
5800 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
5801 DCI.AddToWorklist(Op.getNode());
5802 }
5803 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
5804 DAG.getConstant(Index, DL, MVT::i32));
5805 }
5806 return SDValue();
5807}
5808
5809// Optimize vector operations in scalar value Op on the basis that Op
5810// is truncated to TruncVT.
5811SDValue SystemZTargetLowering::combineTruncateExtract(
5812 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
5813 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
5814 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
5815 // of type TruncVT.
5816 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5817 TruncVT.getSizeInBits() % 8 == 0) {
5818 SDValue Vec = Op.getOperand(0);
5819 EVT VecVT = Vec.getValueType();
5820 if (canTreatAsByteVector(VecVT)) {
5821 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
5822 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
5823 unsigned TruncBytes = TruncVT.getStoreSize();
5824 if (BytesPerElement % TruncBytes == 0) {
5825 // Calculate the value of Y' in the above description. We are
5826 // splitting the original elements into Scale equal-sized pieces
5827 // and for truncation purposes want the last (least-significant)
5828 // of these pieces for IndexN. This is easiest to do by calculating
5829 // the start index of the following element and then subtracting 1.
5830 unsigned Scale = BytesPerElement / TruncBytes;
5831 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
5832
5833 // Defer the creation of the bitcast from X to combineExtract,
5834 // which might be able to optimize the extraction.
5835 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
5836 VecVT.getStoreSize() / TruncBytes);
5837 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
5838 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
5839 }
5840 }
5841 }
5842 }
5843 return SDValue();
5844}
5845
5846SDValue SystemZTargetLowering::combineZERO_EXTEND(
5847 SDNode *N, DAGCombinerInfo &DCI) const {
5848 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
5849 SelectionDAG &DAG = DCI.DAG;
5850 SDValue N0 = N->getOperand(0);
5851 EVT VT = N->getValueType(0);
5852 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
5853 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
5854 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5855 if (TrueOp && FalseOp) {
5856 SDLoc DL(N0);
5857 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
5858 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
5859 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
5860 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
5861 // If N0 has multiple uses, change other uses as well.
5862 if (!N0.hasOneUse()) {
5863 SDValue TruncSelect =
5864 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
5865 DCI.CombineTo(N0.getNode(), TruncSelect);
5866 }
5867 return NewSelect;
5868 }
5869 }
5870 return SDValue();
5871}
5872
5873SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
5874 SDNode *N, DAGCombinerInfo &DCI) const {
5875 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
5876 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
5877 // into (select_cc LHS, RHS, -1, 0, COND)
5878 SelectionDAG &DAG = DCI.DAG;
5879 SDValue N0 = N->getOperand(0);
5880 EVT VT = N->getValueType(0);
5881 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5882 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
5883 N0 = N0.getOperand(0);
5884 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
5885 SDLoc DL(N0);
5886 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
5887 DAG.getConstant(-1, DL, VT), DAG.getConstant(0, DL, VT),
5888 N0.getOperand(2) };
5889 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
5890 }
5891 return SDValue();
5892}
5893
5894SDValue SystemZTargetLowering::combineSIGN_EXTEND(
5895 SDNode *N, DAGCombinerInfo &DCI) const {
5896 // Convert (sext (ashr (shl X, C1), C2)) to
5897 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
5898 // cheap as narrower ones.
5899 SelectionDAG &DAG = DCI.DAG;
5900 SDValue N0 = N->getOperand(0);
5901 EVT VT = N->getValueType(0);
5902 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
5903 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5904 SDValue Inner = N0.getOperand(0);
5905 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
5906 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
5907 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
5908 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
5909 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
5910 EVT ShiftVT = N0.getOperand(1).getValueType();
5911 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
5912 Inner.getOperand(0));
5913 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
5914 DAG.getConstant(NewShlAmt, SDLoc(Inner),
5915 ShiftVT));
5916 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
5917 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
5918 }
5919 }
5920 }
5921 return SDValue();
5922}
5923
5924SDValue SystemZTargetLowering::combineMERGE(
5925 SDNode *N, DAGCombinerInfo &DCI) const {
5926 SelectionDAG &DAG = DCI.DAG;
5927 unsigned Opcode = N->getOpcode();
5928 SDValue Op0 = N->getOperand(0);
5929 SDValue Op1 = N->getOperand(1);
5930 if (Op0.getOpcode() == ISD::BITCAST)
5931 Op0 = Op0.getOperand(0);
5932 if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5933 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
5934 // for v4f32.
5935 if (Op1 == N->getOperand(0))
5936 return Op1;
5937 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
5938 EVT VT = Op1.getValueType();
5939 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
5940 if (ElemBytes <= 4) {
5941 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
5942 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
5943 EVT InVT = VT.changeVectorElementTypeToInteger();
5944 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
5945 SystemZ::VectorBytes / ElemBytes / 2);
5946 if (VT != InVT) {
5947 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
5948 DCI.AddToWorklist(Op1.getNode());
5949 }
5950 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
5951 DCI.AddToWorklist(Op.getNode());
5952 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
5953 }
5954 }
5955 return SDValue();
5956}
5957
5958SDValue SystemZTargetLowering::combineLOAD(
5959 SDNode *N, DAGCombinerInfo &DCI) const {
5960 SelectionDAG &DAG = DCI.DAG;
5961 EVT LdVT = N->getValueType(0);
5962 if (LdVT.isVector() || LdVT.isInteger())
5963 return SDValue();
5964 // Transform a scalar load that is REPLICATEd as well as having other
5965 // use(s) to the form where the other use(s) use the first element of the
5966 // REPLICATE instead of the load. Otherwise instruction selection will not
5967 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
5968 // point loads.
5969
5970 SDValue Replicate;
5971 SmallVector<SDNode*, 8> OtherUses;
5972 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5973 UI != UE; ++UI) {
5974 if (UI->getOpcode() == SystemZISD::REPLICATE) {
5975 if (Replicate)
5976 return SDValue(); // Should never happen
5977 Replicate = SDValue(*UI, 0);
5978 }
5979 else if (UI.getUse().getResNo() == 0)
5980 OtherUses.push_back(*UI);
5981 }
5982 if (!Replicate || OtherUses.empty())
5983 return SDValue();
5984
5985 SDLoc DL(N);
5986 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
5987 Replicate, DAG.getConstant(0, DL, MVT::i32));
5988 // Update uses of the loaded Value while preserving old chains.
5989 for (SDNode *U : OtherUses) {
5990 SmallVector<SDValue, 8> Ops;
5991 for (SDValue Op : U->ops())
5992 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
5993 DAG.UpdateNodeOperands(U, Ops);
5994 }
5995 return SDValue(N, 0);
5996}
5997
5998bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
5999 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
6000 return true;
6001 if (Subtarget.hasVectorEnhancements2())
6002 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64)
6003 return true;
6004 return false;
6005}
6006
6007static bool isVectorElementSwap(ArrayRef<int> M, EVT VT) {
6008 if (!VT.isVector() || !VT.isSimple() ||
6009 VT.getSizeInBits() != 128 ||
6010 VT.getScalarSizeInBits() % 8 != 0)
6011 return false;
6012
6013 unsigned NumElts = VT.getVectorNumElements();
6014 for (unsigned i = 0; i < NumElts; ++i) {
6015 if (M[i] < 0) continue; // ignore UNDEF indices
6016 if ((unsigned) M[i] != NumElts - 1 - i)
6017 return false;
6018 }
6019
6020 return true;
6021}
6022
6023SDValue SystemZTargetLowering::combineSTORE(
6024 SDNode *N, DAGCombinerInfo &DCI) const {
6025 SelectionDAG &DAG = DCI.DAG;
6026 auto *SN = cast<StoreSDNode>(N);
6027 auto &Op1 = N->getOperand(1);
6028 EVT MemVT = SN->getMemoryVT();
6029 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
6030 // for the extraction to be done on a vMiN value, so that we can use VSTE.
6031 // If X has wider elements then convert it to:
6032 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
6033 if (MemVT.isInteger() && SN->isTruncatingStore()) {
6034 if (SDValue Value =
6035 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
6036 DCI.AddToWorklist(Value.getNode());
6037
6038 // Rewrite the store with the new form of stored value.
6039 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
6040 SN->getBasePtr(), SN->getMemoryVT(),
6041 SN->getMemOperand());
6042 }
6043 }
6044 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
6045 if (!SN->isTruncatingStore() &&
6046 Op1.getOpcode() == ISD::BSWAP &&
6047 Op1.getNode()->hasOneUse() &&
6048 canLoadStoreByteSwapped(Op1.getValueType())) {
6049
6050 SDValue BSwapOp = Op1.getOperand(0);
6051
6052 if (BSwapOp.getValueType() == MVT::i16)
6053 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
6054
6055 SDValue Ops[] = {
6056 N->getOperand(0), BSwapOp, N->getOperand(2)
6057 };
6058
6059 return
6060 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
6061 Ops, MemVT, SN->getMemOperand());
6062 }
6063 // Combine STORE (element-swap) into VSTER
6064 if (!SN->isTruncatingStore() &&
6065 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
6066 Op1.getNode()->hasOneUse() &&
6067 Subtarget.hasVectorEnhancements2()) {
6068 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
6069 ArrayRef<int> ShuffleMask = SVN->getMask();
6070 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
6071 SDValue Ops[] = {
6072 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
6073 };
6074
6075 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
6076 DAG.getVTList(MVT::Other),
6077 Ops, MemVT, SN->getMemOperand());
6078 }
6079 }
6080
6081 return SDValue();
6082}
6083
6084SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
6085 SDNode *N, DAGCombinerInfo &DCI) const {
6086 SelectionDAG &DAG = DCI.DAG;
6087 // Combine element-swap (LOAD) into VLER
6088 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6089 N->getOperand(0).hasOneUse() &&
6090 Subtarget.hasVectorEnhancements2()) {
6091 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6092 ArrayRef<int> ShuffleMask = SVN->getMask();
6093 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
6094 SDValue Load = N->getOperand(0);
6095 LoadSDNode *LD = cast<LoadSDNode>(Load);
6096
6097 // Create the element-swapping load.
6098 SDValue Ops[] = {
6099 LD->getChain(), // Chain
6100 LD->getBasePtr() // Ptr
6101 };
6102 SDValue ESLoad =
6103 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
6104 DAG.getVTList(LD->getValueType(0), MVT::Other),
6105 Ops, LD->getMemoryVT(), LD->getMemOperand());
6106
6107 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
6108 // by the load dead.
6109 DCI.CombineTo(N, ESLoad);
6110
6111 // Next, combine the load away, we give it a bogus result value but a real
6112 // chain result. The result value is dead because the shuffle is dead.
6113 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
6114
6115 // Return N so it doesn't get rechecked!
6116 return SDValue(N, 0);
6117 }
6118 }
6119
6120 return SDValue();
6121}
6122
6123SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
6124 SDNode *N, DAGCombinerInfo &DCI) const {
6125 SelectionDAG &DAG = DCI.DAG;
6126
6127 if (!Subtarget.hasVector())
6128 return SDValue();
6129
6130 // Look through bitcasts that retain the number of vector elements.
6131 SDValue Op = N->getOperand(0);
6132 if (Op.getOpcode() == ISD::BITCAST &&
6133 Op.getValueType().isVector() &&
6134 Op.getOperand(0).getValueType().isVector() &&
6135 Op.getValueType().getVectorNumElements() ==
6136 Op.getOperand(0).getValueType().getVectorNumElements())
6137 Op = Op.getOperand(0);
6138
6139 // Pull BSWAP out of a vector extraction.
6140 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
6141 EVT VecVT = Op.getValueType();
6142 EVT EltVT = VecVT.getVectorElementType();
6143 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
6144 Op.getOperand(0), N->getOperand(1));
6145 DCI.AddToWorklist(Op.getNode());
6146 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
6147 if (EltVT != N->getValueType(0)) {
6148 DCI.AddToWorklist(Op.getNode());
6149 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
6150 }
6151 return Op;
6152 }
6153
6154 // Try to simplify a vector extraction.
6155 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6156 SDValue Op0 = N->getOperand(0);
6157 EVT VecVT = Op0.getValueType();
6158 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
6159 IndexN->getZExtValue(), DCI, false);
6160 }
6161 return SDValue();
6162}
6163
6164SDValue SystemZTargetLowering::combineJOIN_DWORDS(
6165 SDNode *N, DAGCombinerInfo &DCI) const {
6166 SelectionDAG &DAG = DCI.DAG;
6167 // (join_dwords X, X) == (replicate X)
6168 if (N->getOperand(0) == N->getOperand(1))
6169 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
6170 N->getOperand(0));
6171 return SDValue();
6172}
6173
6174static SDValue MergeInputChains(SDNode *N1, SDNode *N2) {
6175 SDValue Chain1 = N1->getOperand(0);
6176 SDValue Chain2 = N2->getOperand(0);
6177
6178 // Trivial case: both nodes take the same chain.
6179 if (Chain1 == Chain2)
6180 return Chain1;
6181
6182 // FIXME - we could handle more complex cases via TokenFactor,
6183 // assuming we can verify that this would not create a cycle.
6184 return SDValue();
6185}
6186
6187SDValue SystemZTargetLowering::combineFP_ROUND(
6188 SDNode *N, DAGCombinerInfo &DCI) const {
6189
6190 if (!Subtarget.hasVector())
6191 return SDValue();
6192
6193 // (fpround (extract_vector_elt X 0))
6194 // (fpround (extract_vector_elt X 1)) ->
6195 // (extract_vector_elt (VROUND X) 0)
6196 // (extract_vector_elt (VROUND X) 2)
6197 //
6198 // This is a special case since the target doesn't really support v2f32s.
6199 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
6200 SelectionDAG &DAG = DCI.DAG;
6201 SDValue Op0 = N->getOperand(OpNo);
6202 if (N->getValueType(0) == MVT::f32 &&
6203 Op0.hasOneUse() &&
6204 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6205 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
6206 Op0.getOperand(1).getOpcode() == ISD::Constant &&
6207 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
6208 SDValue Vec = Op0.getOperand(0);
6209 for (auto *U : Vec->uses()) {
6210 if (U != Op0.getNode() &&
6211 U->hasOneUse() &&
6212 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6213 U->getOperand(0) == Vec &&
6214 U->getOperand(1).getOpcode() == ISD::Constant &&
6215 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
6216 SDValue OtherRound = SDValue(*U->use_begin(), 0);
6217 if (OtherRound.getOpcode() == N->getOpcode() &&
6218 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
6219 OtherRound.getValueType() == MVT::f32) {
6220 SDValue VRound, Chain;
6221 if (N->isStrictFPOpcode()) {
6222 Chain = MergeInputChains(N, OtherRound.getNode());
6223 if (!Chain)
6224 continue;
6225 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
6226 {MVT::v4f32, MVT::Other}, {Chain, Vec});
6227 Chain = VRound.getValue(1);
6228 } else
6229 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
6230 MVT::v4f32, Vec);
6231 DCI.AddToWorklist(VRound.getNode());
6232 SDValue Extract1 =
6233 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
6234 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
6235 DCI.AddToWorklist(Extract1.getNode());
6236 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
6237 if (Chain)
6238 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
6239 SDValue Extract0 =
6240 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
6241 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
6242 if (Chain)
6243 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
6244 N->getVTList(), Extract0, Chain);
6245 return Extract0;
6246 }
6247 }
6248 }
6249 }
6250 return SDValue();
6251}
6252
6253SDValue SystemZTargetLowering::combineFP_EXTEND(
6254 SDNode *N, DAGCombinerInfo &DCI) const {
6255
6256 if (!Subtarget.hasVector())
6257 return SDValue();
6258
6259 // (fpextend (extract_vector_elt X 0))
6260 // (fpextend (extract_vector_elt X 2)) ->
6261 // (extract_vector_elt (VEXTEND X) 0)
6262 // (extract_vector_elt (VEXTEND X) 1)
6263 //
6264 // This is a special case since the target doesn't really support v2f32s.
6265 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
6266 SelectionDAG &DAG = DCI.DAG;
6267 SDValue Op0 = N->getOperand(OpNo);
6268 if (N->getValueType(0) == MVT::f64 &&
6269 Op0.hasOneUse() &&
6270 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6271 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
6272 Op0.getOperand(1).getOpcode() == ISD::Constant &&
6273 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
6274 SDValue Vec = Op0.getOperand(0);
6275 for (auto *U : Vec->uses()) {
6276 if (U != Op0.getNode() &&
6277 U->hasOneUse() &&
6278 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6279 U->getOperand(0) == Vec &&
6280 U->getOperand(1).getOpcode() == ISD::Constant &&
6281 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 2) {
6282 SDValue OtherExtend = SDValue(*U->use_begin(), 0);
6283 if (OtherExtend.getOpcode() == N->getOpcode() &&
6284 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
6285 OtherExtend.getValueType() == MVT::f64) {
6286 SDValue VExtend, Chain;
6287 if (N->isStrictFPOpcode()) {
6288 Chain = MergeInputChains(N, OtherExtend.getNode());
6289 if (!Chain)
6290 continue;
6291 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
6292 {MVT::v2f64, MVT::Other}, {Chain, Vec});
6293 Chain = VExtend.getValue(1);
6294 } else
6295 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
6296 MVT::v2f64, Vec);
6297 DCI.AddToWorklist(VExtend.getNode());
6298 SDValue Extract1 =
6299 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
6300 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
6301 DCI.AddToWorklist(Extract1.getNode());
6302 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
6303 if (Chain)
6304 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
6305 SDValue Extract0 =
6306 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
6307 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
6308 if (Chain)
6309 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
6310 N->getVTList(), Extract0, Chain);
6311 return Extract0;
6312 }
6313 }
6314 }
6315 }
6316 return SDValue();
6317}
6318
6319SDValue SystemZTargetLowering::combineINT_TO_FP(
6320 SDNode *N, DAGCombinerInfo &DCI) const {
6321 if (DCI.Level != BeforeLegalizeTypes)
6322 return SDValue();
6323 unsigned Opcode = N->getOpcode();
6324 EVT OutVT = N->getValueType(0);
6325 SelectionDAG &DAG = DCI.DAG;
6326 SDValue Op = N->getOperand(0);
6327 unsigned OutScalarBits = OutVT.getScalarSizeInBits();
6328 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
6329
6330 // Insert an extension before type-legalization to avoid scalarization, e.g.:
6331 // v2f64 = uint_to_fp v2i16
6332 // =>
6333 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
6334 if (OutVT.isVector() && OutScalarBits > InScalarBits) {
6335 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(OutVT.getScalarSizeInBits()),
6336 OutVT.getVectorNumElements());
6337 unsigned ExtOpcode =
6338 (Opcode == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND);
6339 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
6340 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
6341 }
6342 return SDValue();
6343}
6344
6345SDValue SystemZTargetLowering::combineBSWAP(
6346 SDNode *N, DAGCombinerInfo &DCI) const {
6347 SelectionDAG &DAG = DCI.DAG;
6348 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
6349 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6350 N->getOperand(0).hasOneUse() &&
6351 canLoadStoreByteSwapped(N->getValueType(0))) {
6352 SDValue Load = N->getOperand(0);
6353 LoadSDNode *LD = cast<LoadSDNode>(Load);
6354
6355 // Create the byte-swapping load.
6356 SDValue Ops[] = {
6357 LD->getChain(), // Chain
6358 LD->getBasePtr() // Ptr
6359 };
6360 EVT LoadVT = N->getValueType(0);
6361 if (LoadVT == MVT::i16)
6362 LoadVT = MVT::i32;
6363 SDValue BSLoad =
6364 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
6365 DAG.getVTList(LoadVT, MVT::Other),
6366 Ops, LD->getMemoryVT(), LD->getMemOperand());
6367
6368 // If this is an i16 load, insert the truncate.
6369 SDValue ResVal = BSLoad;
6370 if (N->getValueType(0) == MVT::i16)
6371 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
6372
6373 // First, combine the bswap away. This makes the value produced by the
6374 // load dead.
6375 DCI.CombineTo(N, ResVal);
6376
6377 // Next, combine the load away, we give it a bogus result value but a real
6378 // chain result. The result value is dead because the bswap is dead.
6379 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6380
6381 // Return N so it doesn't get rechecked!
6382 return SDValue(N, 0);
6383 }
6384
6385 // Look through bitcasts that retain the number of vector elements.
6386 SDValue Op = N->getOperand(0);
6387 if (Op.getOpcode() == ISD::BITCAST &&
6388 Op.getValueType().isVector() &&
6389 Op.getOperand(0).getValueType().isVector() &&
6390 Op.getValueType().getVectorNumElements() ==
6391 Op.getOperand(0).getValueType().getVectorNumElements())
6392 Op = Op.getOperand(0);
6393
6394 // Push BSWAP into a vector insertion if at least one side then simplifies.
6395 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
6396 SDValue Vec = Op.getOperand(0);
6397 SDValue Elt = Op.getOperand(1);
6398 SDValue Idx = Op.getOperand(2);
6399
6400 if (DAG.isConstantIntBuildVectorOrConstantInt(Vec) ||
6401 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
6402 DAG.isConstantIntBuildVectorOrConstantInt(Elt) ||
6403 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
6404 (canLoadStoreByteSwapped(N->getValueType(0)) &&
6405 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
6406 EVT VecVT = N->getValueType(0);
6407 EVT EltVT = N->getValueType(0).getVectorElementType();
6408 if (VecVT != Vec.getValueType()) {
6409 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
6410 DCI.AddToWorklist(Vec.getNode());
6411 }
6412 if (EltVT != Elt.getValueType()) {
6413 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
6414 DCI.AddToWorklist(Elt.getNode());
6415 }
6416 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
6417 DCI.AddToWorklist(Vec.getNode());
6418 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
6419 DCI.AddToWorklist(Elt.getNode());
6420 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
6421 Vec, Elt, Idx);
6422 }
6423 }
6424
6425 // Push BSWAP into a vector shuffle if at least one side then simplifies.
6426 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
6427 if (SV && Op.hasOneUse()) {
6428 SDValue Op0 = Op.getOperand(0);
6429 SDValue Op1 = Op.getOperand(1);
6430
6431 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
6432 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
6433 DAG.isConstantIntBuildVectorOrConstantInt(Op1) ||
6434 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
6435 EVT VecVT = N->getValueType(0);
6436 if (VecVT != Op0.getValueType()) {
6437 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
6438 DCI.AddToWorklist(Op0.getNode());
6439 }
6440 if (VecVT != Op1.getValueType()) {
6441 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
6442 DCI.AddToWorklist(Op1.getNode());
6443 }
6444 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
6445 DCI.AddToWorklist(Op0.getNode());
6446 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
6447 DCI.AddToWorklist(Op1.getNode());
6448 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
6449 }
6450 }
6451
6452 return SDValue();
6453}
6454
6455static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask) {
6456 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
6457 // set by the CCReg instruction using the CCValid / CCMask masks,
6458 // If the CCReg instruction is itself a ICMP testing the condition
6459 // code set by some other instruction, see whether we can directly
6460 // use that condition code.
6461
6462 // Verify that we have an ICMP against some constant.
6463 if (CCValid != SystemZ::CCMASK_ICMP)
6464 return false;
6465 auto *ICmp = CCReg.getNode();
6466 if (ICmp->getOpcode() != SystemZISD::ICMP)
6467 return false;
6468 auto *CompareLHS = ICmp->getOperand(0).getNode();
6469 auto *CompareRHS = dyn_cast<ConstantSDNode>(ICmp->getOperand(1));
6470 if (!CompareRHS)
6471 return false;
6472
6473 // Optimize the case where CompareLHS is a SELECT_CCMASK.
6474 if (CompareLHS->getOpcode() == SystemZISD::SELECT_CCMASK) {
6475 // Verify that we have an appropriate mask for a EQ or NE comparison.
6476 bool Invert = false;
6477 if (CCMask == SystemZ::CCMASK_CMP_NE)
6478 Invert = !Invert;
6479 else if (CCMask != SystemZ::CCMASK_CMP_EQ)
6480 return false;
6481
6482 // Verify that the ICMP compares against one of select values.
6483 auto *TrueVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(0));
6484 if (!TrueVal)
6485 return false;
6486 auto *FalseVal = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1));
6487 if (!FalseVal)
6488 return false;
6489 if (CompareRHS->getZExtValue() == FalseVal->getZExtValue())
6490 Invert = !Invert;
6491 else if (CompareRHS->getZExtValue() != TrueVal->getZExtValue())
6492 return false;
6493
6494 // Compute the effective CC mask for the new branch or select.
6495 auto *NewCCValid = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(2));
6496 auto *NewCCMask = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(3));
6497 if (!NewCCValid || !NewCCMask)
6498 return false;
6499 CCValid = NewCCValid->getZExtValue();
6500 CCMask = NewCCMask->getZExtValue();
6501 if (Invert)
6502 CCMask ^= CCValid;
6503
6504 // Return the updated CCReg link.
6505 CCReg = CompareLHS->getOperand(4);
6506 return true;
6507 }
6508
6509 // Optimize the case where CompareRHS is (SRA (SHL (IPM))).
6510 if (CompareLHS->getOpcode() == ISD::SRA) {
6511 auto *SRACount = dyn_cast<ConstantSDNode>(CompareLHS->getOperand(1));
6512 if (!SRACount || SRACount->getZExtValue() != 30)
6513 return false;
6514 auto *SHL = CompareLHS->getOperand(0).getNode();
6515 if (SHL->getOpcode() != ISD::SHL)
6516 return false;
6517 auto *SHLCount = dyn_cast<ConstantSDNode>(SHL->getOperand(1));
6518 if (!SHLCount || SHLCount->getZExtValue() != 30 - SystemZ::IPM_CC)
6519 return false;
6520 auto *IPM = SHL->getOperand(0).getNode();
6521 if (IPM->getOpcode() != SystemZISD::IPM)
6522 return false;
6523
6524 // Avoid introducing CC spills (because SRA would clobber CC).
6525 if (!CompareLHS->hasOneUse())
6526 return false;
6527 // Verify that the ICMP compares against zero.
6528 if (CompareRHS->getZExtValue() != 0)
6529 return false;
6530
6531 // Compute the effective CC mask for the new branch or select.
6532 CCMask = SystemZ::reverseCCMask(CCMask);
6533
6534 // Return the updated CCReg link.
6535 CCReg = IPM->getOperand(0);
6536 return true;
6537 }
6538
6539 return false;
6540}
6541
6542SDValue SystemZTargetLowering::combineBR_CCMASK(
6543 SDNode *N, DAGCombinerInfo &DCI) const {
6544 SelectionDAG &DAG = DCI.DAG;
6545
6546 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
6547 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
6548 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
6549 if (!CCValid || !CCMask)
6550 return SDValue();
6551
6552 int CCValidVal = CCValid->getZExtValue();
6553 int CCMaskVal = CCMask->getZExtValue();
6554 SDValue Chain = N->getOperand(0);
6555 SDValue CCReg = N->getOperand(4);
6556
6557 if (combineCCMask(CCReg, CCValidVal, CCMaskVal))
6558 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
6559 Chain,
6560 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
6561 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
6562 N->getOperand(3), CCReg);
6563 return SDValue();
6564}
6565
6566SDValue SystemZTargetLowering::combineSELECT_CCMASK(
6567 SDNode *N, DAGCombinerInfo &DCI) const {
6568 SelectionDAG &DAG = DCI.DAG;
6569
6570 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
6571 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
6572 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
6573 if (!CCValid || !CCMask)
6574 return SDValue();
6575
6576 int CCValidVal = CCValid->getZExtValue();
6577 int CCMaskVal = CCMask->getZExtValue();
6578 SDValue CCReg = N->getOperand(4);
6579
6580 if (combineCCMask(CCReg, CCValidVal, CCMaskVal))
6581 return DAG.getNode(SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0),
6582 N->getOperand(0), N->getOperand(1),
6583 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
6584 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
6585 CCReg);
6586 return SDValue();
6587}
6588
6589
6590SDValue SystemZTargetLowering::combineGET_CCMASK(
6591 SDNode *N, DAGCombinerInfo &DCI) const {
6592
6593 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
6594 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
6595 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
6596 if (!CCValid || !CCMask)
6597 return SDValue();
6598 int CCValidVal = CCValid->getZExtValue();
6599 int CCMaskVal = CCMask->getZExtValue();
6600
6601 SDValue Select = N->getOperand(0);
6602 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
6603 return SDValue();
6604
6605 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
6606 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
6607 if (!SelectCCValid || !SelectCCMask)
6608 return SDValue();
6609 int SelectCCValidVal = SelectCCValid->getZExtValue();
6610 int SelectCCMaskVal = SelectCCMask->getZExtValue();
6611
6612 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
6613 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
6614 if (!TrueVal || !FalseVal)
6615 return SDValue();
6616 if (TrueVal->getZExtValue() != 0 && FalseVal->getZExtValue() == 0)
6617 ;
6618 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() != 0)
6619 SelectCCMaskVal ^= SelectCCValidVal;
6620 else
6621 return SDValue();
6622
6623 if (SelectCCValidVal & ~CCValidVal)
6624 return SDValue();
6625 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
6626 return SDValue();
6627
6628 return Select->getOperand(4);
6629}
6630
6631SDValue SystemZTargetLowering::combineIntDIVREM(
6632 SDNode *N, DAGCombinerInfo &DCI) const {
6633 SelectionDAG &DAG = DCI.DAG;
6634 EVT VT = N->getValueType(0);
6635 // In the case where the divisor is a vector of constants a cheaper
6636 // sequence of instructions can replace the divide. BuildSDIV is called to
6637 // do this during DAG combining, but it only succeeds when it can build a
6638 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
6639 // since it is not Legal but Custom it can only happen before
6640 // legalization. Therefore we must scalarize this early before Combine
6641 // 1. For widened vectors, this is already the result of type legalization.
6642 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
6643 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
6644 return DAG.UnrollVectorOp(N);
6645 return SDValue();
6646}
6647
6648SDValue SystemZTargetLowering::combineINTRINSIC(
6649 SDNode *N, DAGCombinerInfo &DCI) const {
6650 SelectionDAG &DAG = DCI.DAG;
6651
6652 unsigned Id = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
6653 switch (Id) {
6654 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
6655 // or larger is simply a vector load.
6656 case Intrinsic::s390_vll:
6657 case Intrinsic::s390_vlrl:
6658 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
6659 if (C->getZExtValue() >= 15)
6660 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
6661 N->getOperand(3), MachinePointerInfo());
6662 break;
6663 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
6664 case Intrinsic::s390_vstl:
6665 case Intrinsic::s390_vstrl:
6666 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
6667 if (C->getZExtValue() >= 15)
6668 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
6669 N->getOperand(4), MachinePointerInfo());
6670 break;
6671 }
6672
6673 return SDValue();
6674}
6675
6676SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
6677 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
6678 return N->getOperand(0);
6679 return N;
6680}
6681
6682SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
6683 DAGCombinerInfo &DCI) const {
6684 switch(N->getOpcode()) {
6685 default: break;
6686 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
6687 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
6688 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
6689 case SystemZISD::MERGE_HIGH:
6690 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
6691 case ISD::LOAD: return combineLOAD(N, DCI);
6692 case ISD::STORE: return combineSTORE(N, DCI);
6693 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
6694 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
6695 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
6696 case ISD::STRICT_FP_ROUND:
6697 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
6698 case ISD::STRICT_FP_EXTEND:
6699 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
6700 case ISD::SINT_TO_FP:
6701 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
6702 case ISD::BSWAP: return combineBSWAP(N, DCI);
6703 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
6704 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
6705 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
6706 case ISD::SDIV:
6707 case ISD::UDIV:
6708 case ISD::SREM:
6709 case ISD::UREM: return combineIntDIVREM(N, DCI);
6710 case ISD::INTRINSIC_W_CHAIN:
6711 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
6712 }
6713
6714 return SDValue();
6715}
6716
6717// Return the demanded elements for the OpNo source operand of Op. DemandedElts
6718// are for Op.
6719static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
6720 unsigned OpNo) {
6721 EVT VT = Op.getValueType();
6722 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
6723 APInt SrcDemE;
6724 unsigned Opcode = Op.getOpcode();
6725 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
6726 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6727 switch (Id) {
6728 case Intrinsic::s390_vpksh: // PACKS
6729 case Intrinsic::s390_vpksf:
6730 case Intrinsic::s390_vpksg:
6731 case Intrinsic::s390_vpkshs: // PACKS_CC
6732 case Intrinsic::s390_vpksfs:
6733 case Intrinsic::s390_vpksgs:
6734 case Intrinsic::s390_vpklsh: // PACKLS
6735 case Intrinsic::s390_vpklsf:
6736 case Intrinsic::s390_vpklsg:
6737 case Intrinsic::s390_vpklshs: // PACKLS_CC
6738 case Intrinsic::s390_vpklsfs:
6739 case Intrinsic::s390_vpklsgs:
6740 // VECTOR PACK truncates the elements of two source vectors into one.
6741 SrcDemE = DemandedElts;
6742 if (OpNo == 2)
6743 SrcDemE.lshrInPlace(NumElts / 2);
6744 SrcDemE = SrcDemE.trunc(NumElts / 2);
6745 break;
6746 // VECTOR UNPACK extends half the elements of the source vector.
6747 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
6748 case Intrinsic::s390_vuphh:
6749 case Intrinsic::s390_vuphf:
6750 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
6751 case Intrinsic::s390_vuplhh:
6752 case Intrinsic::s390_vuplhf:
6753 SrcDemE = APInt(NumElts * 2, 0);
6754 SrcDemE.insertBits(DemandedElts, 0);
6755 break;
6756 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
6757 case Intrinsic::s390_vuplhw:
6758 case Intrinsic::s390_vuplf:
6759 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
6760 case Intrinsic::s390_vupllh:
6761 case Intrinsic::s390_vupllf:
6762 SrcDemE = APInt(NumElts * 2, 0);
6763 SrcDemE.insertBits(DemandedElts, NumElts);
6764 break;
6765 case Intrinsic::s390_vpdi: {
6766 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
6767 SrcDemE = APInt(NumElts, 0);
6768 if (!DemandedElts[OpNo - 1])
6769 break;
6770 unsigned Mask = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6771 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
6772 // Demand input element 0 or 1, given by the mask bit value.
6773 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
6774 break;
6775 }
6776 case Intrinsic::s390_vsldb: {
6777 // VECTOR SHIFT LEFT DOUBLE BY BYTE
6778 assert(VT == MVT::v16i8 && "Unexpected type.");
6779 unsigned FirstIdx = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6780 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
6781 unsigned NumSrc0Els = 16 - FirstIdx;
6782 SrcDemE = APInt(NumElts, 0);
6783 if (OpNo == 1) {
6784 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
6785 SrcDemE.insertBits(DemEls, FirstIdx);
6786 } else {
6787 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
6788 SrcDemE.insertBits(DemEls, 0);
6789 }
6790 break;
6791 }
6792 case Intrinsic::s390_vperm:
6793 SrcDemE = APInt(NumElts, 1);
6794 break;
6795 default:
6796 llvm_unreachable("Unhandled intrinsic.");
6797 break;
6798 }
6799 } else {
6800 switch (Opcode) {
6801 case SystemZISD::JOIN_DWORDS:
6802 // Scalar operand.
6803 SrcDemE = APInt(1, 1);
6804 break;
6805 case SystemZISD::SELECT_CCMASK:
6806 SrcDemE = DemandedElts;
6807 break;
6808 default:
6809 llvm_unreachable("Unhandled opcode.");
6810 break;
6811 }
6812 }
6813 return SrcDemE;
6814}
6815
6816static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known,
6817 const APInt &DemandedElts,
6818 const SelectionDAG &DAG, unsigned Depth,
6819 unsigned OpNo) {
6820 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
6821 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
6822 KnownBits LHSKnown =
6823 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
6824 KnownBits RHSKnown =
6825 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
6826 Known = KnownBits::commonBits(LHSKnown, RHSKnown);
6827}
6828
6829void
6830SystemZTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
6831 KnownBits &Known,
6832 const APInt &DemandedElts,
6833 const SelectionDAG &DAG,
6834 unsigned Depth) const {
6835 Known.resetAll();
6836
6837 // Intrinsic CC result is returned in the two low bits.
6838 unsigned tmp0, tmp1; // not used
6839 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, tmp0, tmp1)) {
6840 Known.Zero.setBitsFrom(2);
6841 return;
6842 }
6843 EVT VT = Op.getValueType();
6844 if (Op.getResNo() != 0 || VT == MVT::Untyped)
6845 return;
6846 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
6847 "KnownBits does not match VT in bitwidth");
6848 assert ((!VT.isVector() ||
6849 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
6850 "DemandedElts does not match VT number of elements");
6851 unsigned BitWidth = Known.getBitWidth();
6852 unsigned Opcode = Op.getOpcode();
6853 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
6854 bool IsLogical = false;
6855 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6856 switch (Id) {
6857 case Intrinsic::s390_vpksh: // PACKS
6858 case Intrinsic::s390_vpksf:
6859 case Intrinsic::s390_vpksg:
6860 case Intrinsic::s390_vpkshs: // PACKS_CC
6861 case Intrinsic::s390_vpksfs:
6862 case Intrinsic::s390_vpksgs:
6863 case Intrinsic::s390_vpklsh: // PACKLS
6864 case Intrinsic::s390_vpklsf:
6865 case Intrinsic::s390_vpklsg:
6866 case Intrinsic::s390_vpklshs: // PACKLS_CC
6867 case Intrinsic::s390_vpklsfs:
6868 case Intrinsic::s390_vpklsgs:
6869 case Intrinsic::s390_vpdi:
6870 case Intrinsic::s390_vsldb:
6871 case Intrinsic::s390_vperm:
6872 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
6873 break;
6874 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
6875 case Intrinsic::s390_vuplhh:
6876 case Intrinsic::s390_vuplhf:
6877 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
6878 case Intrinsic::s390_vupllh:
6879 case Intrinsic::s390_vupllf:
6880 IsLogical = true;
6881 LLVM_FALLTHROUGH;
6882 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
6883 case Intrinsic::s390_vuphh:
6884 case Intrinsic::s390_vuphf:
6885 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
6886 case Intrinsic::s390_vuplhw:
6887 case Intrinsic::s390_vuplf: {
6888 SDValue SrcOp = Op.getOperand(1);
6889 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
6890 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
6891 if (IsLogical) {
6892 Known = Known.zext(BitWidth);
6893 } else
6894 Known = Known.sext(BitWidth);
6895 break;
6896 }
6897 default:
6898 break;
6899 }
6900 } else {
6901 switch (Opcode) {
6902 case SystemZISD::JOIN_DWORDS:
6903 case SystemZISD::SELECT_CCMASK:
6904 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
6905 break;
6906 case SystemZISD::REPLICATE: {
6907 SDValue SrcOp = Op.getOperand(0);
6908 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
6909 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
6910 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
6911 break;
6912 }
6913 default:
6914 break;
6915 }
6916 }
6917
6918 // Known has the width of the source operand(s). Adjust if needed to match
6919 // the passed bitwidth.
6920 if (Known.getBitWidth() != BitWidth)
6921 Known = Known.anyextOrTrunc(BitWidth);
6922}
6923
6924static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
6925 const SelectionDAG &DAG, unsigned Depth,
6926 unsigned OpNo) {
6927 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
6928 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
6929 if (LHS == 1) return 1; // Early out.
6930 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
6931 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
6932 if (RHS == 1) return 1; // Early out.
6933 unsigned Common = std::min(LHS, RHS);
6934 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
6935 EVT VT = Op.getValueType();
6936 unsigned VTBits = VT.getScalarSizeInBits();
6937 if (SrcBitWidth > VTBits) { // PACK
6938 unsigned SrcExtraBits = SrcBitWidth - VTBits;
6939 if (Common > SrcExtraBits)
6940 return (Common - SrcExtraBits);
6941 return 1;
6942 }
6943 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
6944 return Common;
6945}
6946
6947unsigned
6948SystemZTargetLowering::ComputeNumSignBitsForTargetNode(
6949 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
6950 unsigned Depth) const {
6951 if (Op.getResNo() != 0)
6952 return 1;
6953 unsigned Opcode = Op.getOpcode();
6954 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
6955 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6956 switch (Id) {
6957 case Intrinsic::s390_vpksh: // PACKS
6958 case Intrinsic::s390_vpksf:
6959 case Intrinsic::s390_vpksg:
6960 case Intrinsic::s390_vpkshs: // PACKS_CC
6961 case Intrinsic::s390_vpksfs:
6962 case Intrinsic::s390_vpksgs:
6963 case Intrinsic::s390_vpklsh: // PACKLS
6964 case Intrinsic::s390_vpklsf:
6965 case Intrinsic::s390_vpklsg:
6966 case Intrinsic::s390_vpklshs: // PACKLS_CC
6967 case Intrinsic::s390_vpklsfs:
6968 case Intrinsic::s390_vpklsgs:
6969 case Intrinsic::s390_vpdi:
6970 case Intrinsic::s390_vsldb:
6971 case Intrinsic::s390_vperm:
6972 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
6973 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
6974 case Intrinsic::s390_vuphh:
6975 case Intrinsic::s390_vuphf:
6976 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
6977 case Intrinsic::s390_vuplhw:
6978 case Intrinsic::s390_vuplf: {
6979 SDValue PackedOp = Op.getOperand(1);
6980 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
6981 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
6982 EVT VT = Op.getValueType();
6983 unsigned VTBits = VT.getScalarSizeInBits();
6984 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
6985 return Tmp;
6986 }
6987 default:
6988 break;
6989 }
6990 } else {
6991 switch (Opcode) {
6992 case SystemZISD::SELECT_CCMASK:
6993 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
6994 default:
6995 break;
6996 }
6997 }
6998
6999 return 1;
7000}
7001
7002unsigned
7003SystemZTargetLowering::getStackProbeSize(MachineFunction &MF) const {
7004 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
7005 unsigned StackAlign = TFI->getStackAlignment();
7006 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
7007 "Unexpected stack alignment");
7008 // The default stack probe size is 4096 if the function has no
7009 // stack-probe-size attribute.
7010 unsigned StackProbeSize = 4096;
7011 const Function &Fn = MF.getFunction();
7012 if (Fn.hasFnAttribute("stack-probe-size"))
7013 Fn.getFnAttribute("stack-probe-size")
7014 .getValueAsString()
7015 .getAsInteger(0, StackProbeSize);
7016 // Round down to the stack alignment.
7017 StackProbeSize &= ~(StackAlign - 1);
7018 return StackProbeSize ? StackProbeSize : StackAlign;
7019}
7020
7021//===----------------------------------------------------------------------===//
7022// Custom insertion
7023//===----------------------------------------------------------------------===//
7024
7025// Force base value Base into a register before MI. Return the register.
7026static Register forceReg(MachineInstr &MI, MachineOperand &Base,
7027 const SystemZInstrInfo *TII) {
7028 if (Base.isReg())
7029 return Base.getReg();
7030
7031 MachineBasicBlock *MBB = MI.getParent();
7032 MachineFunction &MF = *MBB->getParent();
7033 MachineRegisterInfo &MRI = MF.getRegInfo();
7034
7035 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
7036 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
7037 .add(Base)
7038 .addImm(0)
7039 .addReg(0);
7040 return Reg;
7041}
7042
7043// The CC operand of MI might be missing a kill marker because there
7044// were multiple uses of CC, and ISel didn't know which to mark.
7045// Figure out whether MI should have had a kill marker.
7046static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB) {
7047 // Scan forward through BB for a use/def of CC.
7048 MachineBasicBlock::iterator miI(std::next(MachineBasicBlock::iterator(MI)));
7049 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
7050 const MachineInstr& mi = *miI;
7051 if (mi.readsRegister(SystemZ::CC))
7052 return false;
7053 if (mi.definesRegister(SystemZ::CC))
7054 break; // Should have kill-flag - update below.
7055 }
7056
7057 // If we hit the end of the block, check whether CC is live into a
7058 // successor.
7059 if (miI == MBB->end()) {
7060 for (auto SI = MBB->succ_begin(), SE = MBB->succ_end(); SI != SE; ++SI)
7061 if ((*SI)->isLiveIn(SystemZ::CC))
7062 return false;
7063 }
7064
7065 return true;
7066}
7067
7068// Return true if it is OK for this Select pseudo-opcode to be cascaded
7069// together with other Select pseudo-opcodes into a single basic-block with
7070// a conditional jump around it.
7071static bool isSelectPseudo(MachineInstr &MI) {
7072 switch (MI.getOpcode()) {
7073 case SystemZ::Select32:
7074 case SystemZ::Select64:
7075 case SystemZ::SelectF32:
7076 case SystemZ::SelectF64:
7077 case SystemZ::SelectF128:
7078 case SystemZ::SelectVR32:
7079 case SystemZ::SelectVR64:
7080 case SystemZ::SelectVR128:
7081 return true;
7082
7083 default:
7084 return false;
7085 }
7086}
7087
7088// Helper function, which inserts PHI functions into SinkMBB:
7089// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
7090// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
7091static void createPHIsForSelects(SmallVector<MachineInstr*, 8> &Selects,
7092 MachineBasicBlock *TrueMBB,
7093 MachineBasicBlock *FalseMBB,
7094 MachineBasicBlock *SinkMBB) {
7095 MachineFunction *MF = TrueMBB->getParent();
7096 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
7097
7098 MachineInstr *FirstMI = Selects.front();
7099 unsigned CCValid = FirstMI->getOperand(3).getImm();
7100 unsigned CCMask = FirstMI->getOperand(4).getImm();
7101
7102 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
7103
7104 // As we are creating the PHIs, we have to be careful if there is more than
7105 // one. Later Selects may reference the results of earlier Selects, but later
7106 // PHIs have to reference the individual true/false inputs from earlier PHIs.
7107 // That also means that PHI construction must work forward from earlier to
7108 // later, and that the code must maintain a mapping from earlier PHI's
7109 // destination registers, and the registers that went into the PHI.
7110 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
7111
7112 for (auto MI : Selects) {
7113 Register DestReg = MI->getOperand(0).getReg();
7114 Register TrueReg = MI->getOperand(1).getReg();
7115 Register FalseReg = MI->getOperand(2).getReg();
7116
7117 // If this Select we are generating is the opposite condition from
7118 // the jump we generated, then we have to swap the operands for the
7119 // PHI that is going to be generated.
7120 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
7121 std::swap(TrueReg, FalseReg);
7122
7123 if (RegRewriteTable.find(TrueReg) != RegRewriteTable.end())
7124 TrueReg = RegRewriteTable[TrueReg].first;
7125
7126 if (RegRewriteTable.find(FalseReg) != RegRewriteTable.end())
7127 FalseReg = RegRewriteTable[FalseReg].second;
7128
7129 DebugLoc DL = MI->getDebugLoc();
7130 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
7131 .addReg(TrueReg).addMBB(TrueMBB)
7132 .addReg(FalseReg).addMBB(FalseMBB);
7133
7134 // Add this PHI to the rewrite table.
7135 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
7136 }
7137
7138 MF->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7139}
7140
7141// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
7142MachineBasicBlock *
7143SystemZTargetLowering::emitSelect(MachineInstr &MI,
7144 MachineBasicBlock *MBB) const {
7145 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
7146 const SystemZInstrInfo *TII =
7147 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7148
7149 unsigned CCValid = MI.getOperand(3).getImm();
7150 unsigned CCMask = MI.getOperand(4).getImm();
7151
7152 // If we have a sequence of Select* pseudo instructions using the
7153 // same condition code value, we want to expand all of them into
7154 // a single pair of basic blocks using the same condition.
7155 SmallVector<MachineInstr*, 8> Selects;
7156 SmallVector<MachineInstr*, 8> DbgValues;
7157 Selects.push_back(&MI);
7158 unsigned Count = 0;
7159 for (MachineBasicBlock::iterator NextMIIt =
7160 std::next(MachineBasicBlock::iterator(MI));
7161 NextMIIt != MBB->end(); ++NextMIIt) {
7162 if (isSelectPseudo(*NextMIIt)) {
7163 assert(NextMIIt->getOperand(3).getImm() == CCValid &&
7164 "Bad CCValid operands since CC was not redefined.");
7165 if (NextMIIt->getOperand(4).getImm() == CCMask ||
7166 NextMIIt->getOperand(4).getImm() == (CCValid ^ CCMask)) {
7167 Selects.push_back(&*NextMIIt);
7168 continue;
7169 }
7170 break;
7171 }
7172 if (NextMIIt->definesRegister(SystemZ::CC) ||
7173 NextMIIt->usesCustomInsertionHook())
7174 break;
7175 bool User = false;
7176 for (auto SelMI : Selects)
7177 if (NextMIIt->readsVirtualRegister(SelMI->getOperand(0).getReg())) {
7178 User = true;
7179 break;
7180 }
7181 if (NextMIIt->isDebugInstr()) {
7182 if (User) {
7183 assert(NextMIIt->isDebugValue() && "Unhandled debug opcode.");
7184 DbgValues.push_back(&*NextMIIt);
7185 }
7186 }
7187 else if (User || ++Count > 20)
7188 break;
7189 }
7190
7191 MachineInstr *LastMI = Selects.back();
7192 bool CCKilled =
7193 (LastMI->killsRegister(SystemZ::CC) || checkCCKill(*LastMI, MBB));
7194 MachineBasicBlock *StartMBB = MBB;
7195 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
7196 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
7197
7198 // Unless CC was killed in the last Select instruction, mark it as
7199 // live-in to both FalseMBB and JoinMBB.
7200 if (!CCKilled) {
7201 FalseMBB->addLiveIn(SystemZ::CC);
7202 JoinMBB->addLiveIn(SystemZ::CC);
7203 }
7204
7205 // StartMBB:
7206 // BRC CCMask, JoinMBB
7207 // # fallthrough to FalseMBB
7208 MBB = StartMBB;
7209 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
7210 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
7211 MBB->addSuccessor(JoinMBB);
7212 MBB->addSuccessor(FalseMBB);
7213
7214 // FalseMBB:
7215 // # fallthrough to JoinMBB
7216 MBB = FalseMBB;
7217 MBB->addSuccessor(JoinMBB);
7218
7219 // JoinMBB:
7220 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
7221 // ...
7222 MBB = JoinMBB;
7223 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
7224 for (auto SelMI : Selects)
7225 SelMI->eraseFromParent();
7226
7227 MachineBasicBlock::iterator InsertPos = MBB->getFirstNonPHI();
7228 for (auto DbgMI : DbgValues)
7229 MBB->splice(InsertPos, StartMBB, DbgMI);
7230
7231 return JoinMBB;
7232}
7233
7234// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
7235// StoreOpcode is the store to use and Invert says whether the store should
7236// happen when the condition is false rather than true. If a STORE ON
7237// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
7238MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
7239 MachineBasicBlock *MBB,
7240 unsigned StoreOpcode,
7241 unsigned STOCOpcode,
7242 bool Invert) const {
7243 const SystemZInstrInfo *TII =
7244 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7245
7246 Register SrcReg = MI.getOperand(0).getReg();
7247 MachineOperand Base = MI.getOperand(1);
7248 int64_t Disp = MI.getOperand(2).getImm();
7249 Register IndexReg = MI.getOperand(3).getReg();
7250 unsigned CCValid = MI.getOperand(4).getImm();
7251 unsigned CCMask = MI.getOperand(5).getImm();
7252 DebugLoc DL = MI.getDebugLoc();
7253
7254 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
7255
7256 // ISel pattern matching also adds a load memory operand of the same
7257 // address, so take special care to find the storing memory operand.
7258 MachineMemOperand *MMO = nullptr;
7259 for (auto *I : MI.memoperands())
7260 if (I->isStore()) {
7261 MMO = I;
7262 break;
7263 }
7264
7265 // Use STOCOpcode if possible. We could use different store patterns in
7266 // order to avoid matching the index register, but the performance trade-offs
7267 // might be more complicated in that case.
7268 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
7269 if (Invert)
7270 CCMask ^= CCValid;
7271
7272 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
7273 .addReg(SrcReg)
7274 .add(Base)
7275 .addImm(Disp)
7276 .addImm(CCValid)
7277 .addImm(CCMask)
7278 .addMemOperand(MMO);
7279
7280 MI.eraseFromParent();
7281 return MBB;
7282 }
7283
7284 // Get the condition needed to branch around the store.
7285 if (!Invert)
7286 CCMask ^= CCValid;
7287
7288 MachineBasicBlock *StartMBB = MBB;
7289 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
7290 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
7291
7292 // Unless CC was killed in the CondStore instruction, mark it as
7293 // live-in to both FalseMBB and JoinMBB.
7294 if (!MI.killsRegister(SystemZ::CC) && !checkCCKill(MI, JoinMBB)) {
7295 FalseMBB->addLiveIn(SystemZ::CC);
7296 JoinMBB->addLiveIn(SystemZ::CC);
7297 }
7298
7299 // StartMBB:
7300 // BRC CCMask, JoinMBB
7301 // # fallthrough to FalseMBB
7302 MBB = StartMBB;
7303 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7304 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
7305 MBB->addSuccessor(JoinMBB);
7306 MBB->addSuccessor(FalseMBB);
7307
7308 // FalseMBB:
7309 // store %SrcReg, %Disp(%Index,%Base)
7310 // # fallthrough to JoinMBB
7311 MBB = FalseMBB;
7312 BuildMI(MBB, DL, TII->get(StoreOpcode))
7313 .addReg(SrcReg)
7314 .add(Base)
7315 .addImm(Disp)
7316 .addReg(IndexReg)
7317 .addMemOperand(MMO);
7318 MBB->addSuccessor(JoinMBB);
7319
7320 MI.eraseFromParent();
7321 return JoinMBB;
7322}
7323
7324// Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
7325// or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that
7326// performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
7327// BitSize is the width of the field in bits, or 0 if this is a partword
7328// ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
7329// is one of the operands. Invert says whether the field should be
7330// inverted after performing BinOpcode (e.g. for NAND).
7331MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
7332 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
7333 unsigned BitSize, bool Invert) const {
7334 MachineFunction &MF = *MBB->getParent();
7335 const SystemZInstrInfo *TII =
7336 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7337 MachineRegisterInfo &MRI = MF.getRegInfo();
7338 bool IsSubWord = (BitSize < 32);
7339
7340 // Extract the operands. Base can be a register or a frame index.
7341 // Src2 can be a register or immediate.
7342 Register Dest = MI.getOperand(0).getReg();
7343 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
7344 int64_t Disp = MI.getOperand(2).getImm();
7345 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
7346 Register BitShift = IsSubWord ? MI.getOperand(4).getReg() : Register();
7347 Register NegBitShift = IsSubWord ? MI.getOperand(5).getReg() : Register();
7348 DebugLoc DL = MI.getDebugLoc();
7349 if (IsSubWord)
7350 BitSize = MI.getOperand(6).getImm();
7351
7352 // Subword operations use 32-bit registers.
7353 const TargetRegisterClass *RC = (BitSize <= 32 ?
7354 &SystemZ::GR32BitRegClass :
7355 &SystemZ::GR64BitRegClass);
7356 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
7357 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
7358
7359 // Get the right opcodes for the displacement.
7360 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
7361 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
7362 assert(LOpcode && CSOpcode && "Displacement out of range");
7363
7364 // Create virtual registers for temporary results.
7365 Register OrigVal = MRI.createVirtualRegister(RC);
7366 Register OldVal = MRI.createVirtualRegister(RC);
7367 Register NewVal = (BinOpcode || IsSubWord ?
7368 MRI.createVirtualRegister(RC) : Src2.getReg());
7369 Register RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
7370 Register RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
7371
7372 // Insert a basic block for the main loop.
7373 MachineBasicBlock *StartMBB = MBB;
7374 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
7375 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
7376
7377 // StartMBB:
7378 // ...
7379 // %OrigVal = L Disp(%Base)
7380 // # fall through to LoopMMB
7381 MBB = StartMBB;
7382 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
7383 MBB->addSuccessor(LoopMBB);
7384
7385 // LoopMBB:
7386 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
7387 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
7388 // %RotatedNewVal = OP %RotatedOldVal, %Src2
7389 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
7390 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
7391 // JNE LoopMBB
7392 // # fall through to DoneMMB
7393 MBB = LoopMBB;
7394 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
7395 .addReg(OrigVal).addMBB(StartMBB)
7396 .addReg(Dest).addMBB(LoopMBB);
7397 if (IsSubWord)
7398 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
7399 .addReg(OldVal).addReg(BitShift).addImm(0);
7400 if (Invert) {
7401 // Perform the operation normally and then invert every bit of the field.
7402 Register Tmp = MRI.createVirtualRegister(RC);
7403 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp).addReg(RotatedOldVal).add(Src2);
7404 if (BitSize <= 32)
7405 // XILF with the upper BitSize bits set.
7406 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
7407 .addReg(Tmp).addImm(-1U << (32 - BitSize));
7408 else {
7409 // Use LCGR and add -1 to the result, which is more compact than
7410 // an XILF, XILH pair.
7411 Register Tmp2 = MRI.createVirtualRegister(RC);
7412 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
7413 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
7414 .addReg(Tmp2).addImm(-1);
7415 }
7416 } else if (BinOpcode)
7417 // A simply binary operation.
7418 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
7419 .addReg(RotatedOldVal)
7420 .add(Src2);
7421 else if (IsSubWord)
7422 // Use RISBG to rotate Src2 into position and use it to replace the
7423 // field in RotatedOldVal.
7424 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
7425 .addReg(RotatedOldVal).addReg(Src2.getReg())
7426 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
7427 if (IsSubWord)
7428 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
7429 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
7430 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
7431 .addReg(OldVal)
7432 .addReg(NewVal)
7433 .add(Base)
7434 .addImm(Disp);
7435 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7436 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
7437 MBB->addSuccessor(LoopMBB);
7438 MBB->addSuccessor(DoneMBB);
7439
7440 MI.eraseFromParent();
7441 return DoneMBB;
7442}
7443
7444// Implement EmitInstrWithCustomInserter for pseudo
7445// ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
7446// instruction that should be used to compare the current field with the
7447// minimum or maximum value. KeepOldMask is the BRC condition-code mask
7448// for when the current field should be kept. BitSize is the width of
7449// the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
7450MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
7451 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
7452 unsigned KeepOldMask, unsigned BitSize) const {
7453 MachineFunction &MF = *MBB->getParent();
7454 const SystemZInstrInfo *TII =
7455 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7456 MachineRegisterInfo &MRI = MF.getRegInfo();
7457 bool IsSubWord = (BitSize < 32);
7458
7459 // Extract the operands. Base can be a register or a frame index.
7460 Register Dest = MI.getOperand(0).getReg();
7461 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
7462 int64_t Disp = MI.getOperand(2).getImm();
7463 Register Src2 = MI.getOperand(3).getReg();
7464 Register BitShift = (IsSubWord ? MI.getOperand(4).getReg() : Register());
7465 Register NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : Register());
7466 DebugLoc DL = MI.getDebugLoc();
7467 if (IsSubWord)
7468 BitSize = MI.getOperand(6).getImm();
7469
7470 // Subword operations use 32-bit registers.
7471 const TargetRegisterClass *RC = (BitSize <= 32 ?
7472 &SystemZ::GR32BitRegClass :
7473 &SystemZ::GR64BitRegClass);
7474 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
7475 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
7476
7477 // Get the right opcodes for the displacement.
7478 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
7479 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
7480 assert(LOpcode && CSOpcode && "Displacement out of range");
7481
7482 // Create virtual registers for temporary results.
7483 Register OrigVal = MRI.createVirtualRegister(RC);
7484 Register OldVal = MRI.createVirtualRegister(RC);
7485 Register NewVal = MRI.createVirtualRegister(RC);
7486 Register RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
7487 Register RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
7488 Register RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
7489
7490 // Insert 3 basic blocks for the loop.
7491 MachineBasicBlock *StartMBB = MBB;
7492 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
7493 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
7494 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
7495 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
7496
7497 // StartMBB:
7498 // ...
7499 // %OrigVal = L Disp(%Base)
7500 // # fall through to LoopMMB
7501 MBB = StartMBB;
7502 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
7503 MBB->addSuccessor(LoopMBB);
7504
7505 // LoopMBB:
7506 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
7507 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
7508 // CompareOpcode %RotatedOldVal, %Src2
7509 // BRC KeepOldMask, UpdateMBB
7510 MBB = LoopMBB;
7511 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
7512 .addReg(OrigVal).addMBB(StartMBB)
7513 .addReg(Dest).addMBB(UpdateMBB);
7514 if (IsSubWord)
7515 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
7516 .addReg(OldVal).addReg(BitShift).addImm(0);
7517 BuildMI(MBB, DL, TII->get(CompareOpcode))
7518 .addReg(RotatedOldVal).addReg(Src2);
7519 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7520 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
7521 MBB->addSuccessor(UpdateMBB);
7522 MBB->addSuccessor(UseAltMBB);
7523
7524 // UseAltMBB:
7525 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
7526 // # fall through to UpdateMMB
7527 MBB = UseAltMBB;
7528 if (IsSubWord)
7529 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
7530 .addReg(RotatedOldVal).addReg(Src2)
7531 .addImm(32).addImm(31 + BitSize).addImm(0);
7532 MBB->addSuccessor(UpdateMBB);
7533
7534 // UpdateMBB:
7535 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
7536 // [ %RotatedAltVal, UseAltMBB ]
7537 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
7538 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
7539 // JNE LoopMBB
7540 // # fall through to DoneMMB
7541 MBB = UpdateMBB;
7542 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
7543 .addReg(RotatedOldVal).addMBB(LoopMBB)
7544 .addReg(RotatedAltVal).addMBB(UseAltMBB);
7545 if (IsSubWord)
7546 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
7547 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
7548 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
7549 .addReg(OldVal)
7550 .addReg(NewVal)
7551 .add(Base)
7552 .addImm(Disp);
7553 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7554 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
7555 MBB->addSuccessor(LoopMBB);
7556 MBB->addSuccessor(DoneMBB);
7557
7558 MI.eraseFromParent();
7559 return DoneMBB;
7560}
7561
7562// Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
7563// instruction MI.
7564MachineBasicBlock *
7565SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
7566 MachineBasicBlock *MBB) const {
7567
7568 MachineFunction &MF = *MBB->getParent();
7569 const SystemZInstrInfo *TII =
7570 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7571 MachineRegisterInfo &MRI = MF.getRegInfo();
7572
7573 // Extract the operands. Base can be a register or a frame index.
7574 Register Dest = MI.getOperand(0).getReg();
7575 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
7576 int64_t Disp = MI.getOperand(2).getImm();
7577 Register OrigCmpVal = MI.getOperand(3).getReg();
7578 Register OrigSwapVal = MI.getOperand(4).getReg();
7579 Register BitShift = MI.getOperand(5).getReg();
7580 Register NegBitShift = MI.getOperand(6).getReg();
7581 int64_t BitSize = MI.getOperand(7).getImm();
7582 DebugLoc DL = MI.getDebugLoc();
7583
7584 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
7585
7586 // Get the right opcodes for the displacement.
7587 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
7588 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
7589 assert(LOpcode && CSOpcode && "Displacement out of range");
7590
7591 // Create virtual registers for temporary results.
7592 Register OrigOldVal = MRI.createVirtualRegister(RC);
7593 Register OldVal = MRI.createVirtualRegister(RC);
7594 Register CmpVal = MRI.createVirtualRegister(RC);
7595 Register SwapVal = MRI.createVirtualRegister(RC);
7596 Register StoreVal = MRI.createVirtualRegister(RC);
7597 Register RetryOldVal = MRI.createVirtualRegister(RC);
7598 Register RetryCmpVal = MRI.createVirtualRegister(RC);
7599 Register RetrySwapVal = MRI.createVirtualRegister(RC);
7600
7601 // Insert 2 basic blocks for the loop.
7602 MachineBasicBlock *StartMBB = MBB;
7603 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
7604 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
7605 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
7606
7607 // StartMBB:
7608 // ...
7609 // %OrigOldVal = L Disp(%Base)
7610 // # fall through to LoopMMB
7611 MBB = StartMBB;
7612 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
7613 .add(Base)
7614 .addImm(Disp)
7615 .addReg(0);
7616 MBB->addSuccessor(LoopMBB);
7617
7618 // LoopMBB:
7619 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
7620 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
7621 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
7622 // %Dest = RLL %OldVal, BitSize(%BitShift)
7623 // ^^ The low BitSize bits contain the field
7624 // of interest.
7625 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
7626 // ^^ Replace the upper 32-BitSize bits of the
7627 // comparison value with those that we loaded,
7628 // so that we can use a full word comparison.
7629 // CR %Dest, %RetryCmpVal
7630 // JNE DoneMBB
7631 // # Fall through to SetMBB
7632 MBB = LoopMBB;
7633 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
7634 .addReg(OrigOldVal).addMBB(StartMBB)
7635 .addReg(RetryOldVal).addMBB(SetMBB);
7636 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
7637 .addReg(OrigCmpVal).addMBB(StartMBB)
7638 .addReg(RetryCmpVal).addMBB(SetMBB);
7639 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
7640 .addReg(OrigSwapVal).addMBB(StartMBB)
7641 .addReg(RetrySwapVal).addMBB(SetMBB);
7642 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
7643 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
7644 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
7645 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
7646 BuildMI(MBB, DL, TII->get(SystemZ::CR))
7647 .addReg(Dest).addReg(RetryCmpVal);
7648 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7649 .addImm(SystemZ::CCMASK_ICMP)
7650 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
7651 MBB->addSuccessor(DoneMBB);
7652 MBB->addSuccessor(SetMBB);
7653
7654 // SetMBB:
7655 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
7656 // ^^ Replace the upper 32-BitSize bits of the new
7657 // value with those that we loaded.
7658 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
7659 // ^^ Rotate the new field to its proper position.
7660 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
7661 // JNE LoopMBB
7662 // # fall through to ExitMMB
7663 MBB = SetMBB;
7664 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
7665 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
7666 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
7667 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
7668 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
7669 .addReg(OldVal)
7670 .addReg(StoreVal)
7671 .add(Base)
7672 .addImm(Disp);
7673 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7674 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
7675 MBB->addSuccessor(LoopMBB);
7676 MBB->addSuccessor(DoneMBB);
7677
7678 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
7679 // to the block after the loop. At this point, CC may have been defined
7680 // either by the CR in LoopMBB or by the CS in SetMBB.
7681 if (!MI.registerDefIsDead(SystemZ::CC))
7682 DoneMBB->addLiveIn(SystemZ::CC);
7683
7684 MI.eraseFromParent();
7685 return DoneMBB;
7686}
7687
7688// Emit a move from two GR64s to a GR128.
7689MachineBasicBlock *
7690SystemZTargetLowering::emitPair128(MachineInstr &MI,
7691 MachineBasicBlock *MBB) const {
7692 MachineFunction &MF = *MBB->getParent();
7693 const SystemZInstrInfo *TII =
7694 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7695 MachineRegisterInfo &MRI = MF.getRegInfo();
7696 DebugLoc DL = MI.getDebugLoc();
7697
7698 Register Dest = MI.getOperand(0).getReg();
7699 Register Hi = MI.getOperand(1).getReg();
7700 Register Lo = MI.getOperand(2).getReg();
7701 Register Tmp1 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7702 Register Tmp2 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7703
7704 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Tmp1);
7705 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Tmp2)
7706 .addReg(Tmp1).addReg(Hi).addImm(SystemZ::subreg_h64);
7707 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
7708 .addReg(Tmp2).addReg(Lo).addImm(SystemZ::subreg_l64);
7709
7710 MI.eraseFromParent();
7711 return MBB;
7712}
7713
7714// Emit an extension from a GR64 to a GR128. ClearEven is true
7715// if the high register of the GR128 value must be cleared or false if
7716// it's "don't care".
7717MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
7718 MachineBasicBlock *MBB,
7719 bool ClearEven) const {
7720 MachineFunction &MF = *MBB->getParent();
7721 const SystemZInstrInfo *TII =
7722 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7723 MachineRegisterInfo &MRI = MF.getRegInfo();
7724 DebugLoc DL = MI.getDebugLoc();
7725
7726 Register Dest = MI.getOperand(0).getReg();
7727 Register Src = MI.getOperand(1).getReg();
7728 Register In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7729
7730 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
7731 if (ClearEven) {
7732 Register NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
7733 Register Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
7734
7735 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
7736 .addImm(0);
7737 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
7738 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
7739 In128 = NewIn128;
7740 }
7741 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
7742 .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64);
7743
7744 MI.eraseFromParent();
7745 return MBB;
7746}
7747
7748MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper(
7749 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
7750 MachineFunction &MF = *MBB->getParent();
7751 const SystemZInstrInfo *TII =
7752 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7753 MachineRegisterInfo &MRI = MF.getRegInfo();
7754 DebugLoc DL = MI.getDebugLoc();
7755
7756 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
7757 uint64_t DestDisp = MI.getOperand(1).getImm();
7758 MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2));
7759 uint64_t SrcDisp = MI.getOperand(3).getImm();
7760 uint64_t Length = MI.getOperand(4).getImm();
7761
7762 // When generating more than one CLC, all but the last will need to
7763 // branch to the end when a difference is found.
7764 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
7765 SystemZ::splitBlockAfter(MI, MBB) : nullptr);
7766
7767 // Check for the loop form, in which operand 5 is the trip count.
7768 if (MI.getNumExplicitOperands() > 5) {
7769 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
7770
7771 Register StartCountReg = MI.getOperand(5).getReg();
7772 Register StartSrcReg = forceReg(MI, SrcBase, TII);
7773 Register StartDestReg = (HaveSingleBase ? StartSrcReg :
7774 forceReg(MI, DestBase, TII));
7775
7776 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
7777 Register ThisSrcReg = MRI.createVirtualRegister(RC);
7778 Register ThisDestReg = (HaveSingleBase ? ThisSrcReg :
7779 MRI.createVirtualRegister(RC));
7780 Register NextSrcReg = MRI.createVirtualRegister(RC);
7781 Register NextDestReg = (HaveSingleBase ? NextSrcReg :
7782 MRI.createVirtualRegister(RC));
7783
7784 RC = &SystemZ::GR64BitRegClass;
7785 Register ThisCountReg = MRI.createVirtualRegister(RC);
7786 Register NextCountReg = MRI.createVirtualRegister(RC);
7787
7788 MachineBasicBlock *StartMBB = MBB;
7789 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
7790 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
7791 MachineBasicBlock *NextMBB =
7792 (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
7793
7794 // StartMBB:
7795 // # fall through to LoopMMB
7796 MBB->addSuccessor(LoopMBB);
7797
7798 // LoopMBB:
7799 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
7800 // [ %NextDestReg, NextMBB ]
7801 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
7802 // [ %NextSrcReg, NextMBB ]
7803 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
7804 // [ %NextCountReg, NextMBB ]
7805 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
7806 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
7807 // ( JLH EndMBB )
7808 //
7809 // The prefetch is used only for MVC. The JLH is used only for CLC.
7810 MBB = LoopMBB;
7811
7812 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
7813 .addReg(StartDestReg).addMBB(StartMBB)
7814 .addReg(NextDestReg).addMBB(NextMBB);
7815 if (!HaveSingleBase)
7816 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
7817 .addReg(StartSrcReg).addMBB(StartMBB)
7818 .addReg(NextSrcReg).addMBB(NextMBB);
7819 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
7820 .addReg(StartCountReg).addMBB(StartMBB)
7821 .addReg(NextCountReg).addMBB(NextMBB);
7822 if (Opcode == SystemZ::MVC)
7823 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
7824 .addImm(SystemZ::PFD_WRITE)
7825 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
7826 BuildMI(MBB, DL, TII->get(Opcode))
7827 .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
7828 .addReg(ThisSrcReg).addImm(SrcDisp);
7829 if (EndMBB) {
7830 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7831 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
7832 .addMBB(EndMBB);
7833 MBB->addSuccessor(EndMBB);
7834 MBB->addSuccessor(NextMBB);
7835 }
7836
7837 // NextMBB:
7838 // %NextDestReg = LA 256(%ThisDestReg)
7839 // %NextSrcReg = LA 256(%ThisSrcReg)
7840 // %NextCountReg = AGHI %ThisCountReg, -1
7841 // CGHI %NextCountReg, 0
7842 // JLH LoopMBB
7843 // # fall through to DoneMMB
7844 //
7845 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
7846 MBB = NextMBB;
7847
7848 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
7849 .addReg(ThisDestReg).addImm(256).addReg(0);
7850 if (!HaveSingleBase)
7851 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
7852 .addReg(ThisSrcReg).addImm(256).addReg(0);
7853 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
7854 .addReg(ThisCountReg).addImm(-1);
7855 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
7856 .addReg(NextCountReg).addImm(0);
7857 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7858 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
7859 .addMBB(LoopMBB);
7860 MBB->addSuccessor(LoopMBB);
7861 MBB->addSuccessor(DoneMBB);
7862
7863 DestBase = MachineOperand::CreateReg(NextDestReg, false);
7864 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
7865 Length &= 255;
7866 if (EndMBB && !Length)
7867 // If the loop handled the whole CLC range, DoneMBB will be empty with
7868 // CC live-through into EndMBB, so add it as live-in.
7869 DoneMBB->addLiveIn(SystemZ::CC);
7870 MBB = DoneMBB;
7871 }
7872 // Handle any remaining bytes with straight-line code.
7873 while (Length > 0) {
7874 uint64_t ThisLength = std::min(Length, uint64_t(256));
7875 // The previous iteration might have created out-of-range displacements.
7876 // Apply them using LAY if so.
7877 if (!isUInt<12>(DestDisp)) {
7878 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
7879 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
7880 .add(DestBase)
7881 .addImm(DestDisp)
7882 .addReg(0);
7883 DestBase = MachineOperand::CreateReg(Reg, false);
7884 DestDisp = 0;
7885 }
7886 if (!isUInt<12>(SrcDisp)) {
7887 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
7888 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
7889 .add(SrcBase)
7890 .addImm(SrcDisp)
7891 .addReg(0);
7892 SrcBase = MachineOperand::CreateReg(Reg, false);
7893 SrcDisp = 0;
7894 }
7895 BuildMI(*MBB, MI, DL, TII->get(Opcode))
7896 .add(DestBase)
7897 .addImm(DestDisp)
7898 .addImm(ThisLength)
7899 .add(SrcBase)
7900 .addImm(SrcDisp)
7901 .setMemRefs(MI.memoperands());
7902 DestDisp += ThisLength;
7903 SrcDisp += ThisLength;
7904 Length -= ThisLength;
7905 // If there's another CLC to go, branch to the end if a difference
7906 // was found.
7907 if (EndMBB && Length > 0) {
7908 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
7909 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7910 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
7911 .addMBB(EndMBB);
7912 MBB->addSuccessor(EndMBB);
7913 MBB->addSuccessor(NextMBB);
7914 MBB = NextMBB;
7915 }
7916 }
7917 if (EndMBB) {
7918 MBB->addSuccessor(EndMBB);
7919 MBB = EndMBB;
7920 MBB->addLiveIn(SystemZ::CC);
7921 }
7922
7923 MI.eraseFromParent();
7924 return MBB;
7925}
7926
7927// Decompose string pseudo-instruction MI into a loop that continually performs
7928// Opcode until CC != 3.
7929MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
7930 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
7931 MachineFunction &MF = *MBB->getParent();
7932 const SystemZInstrInfo *TII =
7933 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
7934 MachineRegisterInfo &MRI = MF.getRegInfo();
7935 DebugLoc DL = MI.getDebugLoc();
7936
7937 uint64_t End1Reg = MI.getOperand(0).getReg();
7938 uint64_t Start1Reg = MI.getOperand(1).getReg();
7939 uint64_t Start2Reg = MI.getOperand(2).getReg();
7940 uint64_t CharReg = MI.getOperand(3).getReg();
7941
7942 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
7943 uint64_t This1Reg = MRI.createVirtualRegister(RC);
7944 uint64_t This2Reg = MRI.createVirtualRegister(RC);
7945 uint64_t End2Reg = MRI.createVirtualRegister(RC);
7946
7947 MachineBasicBlock *StartMBB = MBB;
7948 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
7949 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
7950
7951 // StartMBB:
7952 // # fall through to LoopMMB
7953 MBB->addSuccessor(LoopMBB);
7954
7955 // LoopMBB:
7956 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
7957 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
7958 // R0L = %CharReg
7959 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
7960 // JO LoopMBB
7961 // # fall through to DoneMMB
7962 //
7963 // The load of R0L can be hoisted by post-RA LICM.
7964 MBB = LoopMBB;
7965
7966 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
7967 .addReg(Start1Reg).addMBB(StartMBB)
7968 .addReg(End1Reg).addMBB(LoopMBB);
7969 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
7970 .addReg(Start2Reg).addMBB(StartMBB)
7971 .addReg(End2Reg).addMBB(LoopMBB);
7972 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
7973 BuildMI(MBB, DL, TII->get(Opcode))
7974 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
7975 .addReg(This1Reg).addReg(This2Reg);
7976 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
7977 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
7978 MBB->addSuccessor(LoopMBB);
7979 MBB->addSuccessor(DoneMBB);
7980
7981 DoneMBB->addLiveIn(SystemZ::CC);
7982
7983 MI.eraseFromParent();
7984 return DoneMBB;
7985}
7986
7987// Update TBEGIN instruction with final opcode and register clobbers.
7988MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
7989 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
7990 bool NoFloat) const {
7991 MachineFunction &MF = *MBB->getParent();
7992 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
7993 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
7994
7995 // Update opcode.
7996 MI.setDesc(TII->get(Opcode));
7997
7998 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
7999 // Make sure to add the corresponding GRSM bits if they are missing.
8000 uint64_t Control = MI.getOperand(2).getImm();
8001 static const unsigned GPRControlBit[16] = {
8002 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
8003 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
8004 };
8005 Control |= GPRControlBit[15];
8006 if (TFI->hasFP(MF))
8007 Control |= GPRControlBit[11];
8008 MI.getOperand(2).setImm(Control);
8009
8010 // Add GPR clobbers.
8011 for (int I = 0; I < 16; I++) {
8012 if ((Control & GPRControlBit[I]) == 0) {
8013 unsigned Reg = SystemZMC::GR64Regs[I];
8014 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
8015 }
8016 }
8017
8018 // Add FPR/VR clobbers.
8019 if (!NoFloat && (Control & 4) != 0) {
8020 if (Subtarget.hasVector()) {
8021 for (int I = 0; I < 32; I++) {
8022 unsigned Reg = SystemZMC::VR128Regs[I];
8023 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
8024 }
8025 } else {
8026 for (int I = 0; I < 16; I++) {
8027 unsigned Reg = SystemZMC::FP64Regs[I];
8028 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
8029 }
8030 }
8031 }
8032
8033 return MBB;
8034}
8035
8036MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
8037 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
8038 MachineFunction &MF = *MBB->getParent();
8039 MachineRegisterInfo *MRI = &MF.getRegInfo();
8040 const SystemZInstrInfo *TII =
8041 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
8042 DebugLoc DL = MI.getDebugLoc();
8043
8044 Register SrcReg = MI.getOperand(0).getReg();
8045
8046 // Create new virtual register of the same class as source.
8047 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
8048 Register DstReg = MRI->createVirtualRegister(RC);
8049
8050 // Replace pseudo with a normal load-and-test that models the def as
8051 // well.
8052 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
8053 .addReg(SrcReg)
8054 .setMIFlags(MI.getFlags());
8055 MI.eraseFromParent();
8056
8057 return MBB;
8058}
8059
8060MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
8061 MachineInstr &MI, MachineBasicBlock *MBB) const {
8062 MachineFunction &MF = *MBB->getParent();
8063 MachineRegisterInfo *MRI = &MF.getRegInfo();
8064 const SystemZInstrInfo *TII =
8065 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
8066 DebugLoc DL = MI.getDebugLoc();
8067 const unsigned ProbeSize = getStackProbeSize(MF);
8068 Register DstReg = MI.getOperand(0).getReg();
8069 Register SizeReg = MI.getOperand(2).getReg();
8070
8071 MachineBasicBlock *StartMBB = MBB;
8072 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
8073 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
8074 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
8075 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
8076 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
8077
8078 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
8079 MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad, 8, Align(1));
8080
8081 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
8082 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
8083
8084 // LoopTestMBB
8085 // BRC TailTestMBB
8086 // # fallthrough to LoopBodyMBB
8087 StartMBB->addSuccessor(LoopTestMBB);
8088 MBB = LoopTestMBB;
8089 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
8090 .addReg(SizeReg)
8091 .addMBB(StartMBB)
8092 .addReg(IncReg)
8093 .addMBB(LoopBodyMBB);
8094 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
8095 .addReg(PHIReg)
8096 .addImm(ProbeSize);
8097 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
8098 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_LT)
8099 .addMBB(TailTestMBB);
8100 MBB->addSuccessor(LoopBodyMBB);
8101 MBB->addSuccessor(TailTestMBB);
8102
8103 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
8104 // J LoopTestMBB
8105 MBB = LoopBodyMBB;
8106 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
8107 .addReg(PHIReg)
8108 .addImm(ProbeSize);
8109 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
8110 .addReg(SystemZ::R15D)
8111 .addImm(ProbeSize);
8112 BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D)
8113 .addReg(SystemZ::R15D).addImm(ProbeSize - 8).addReg(0)
8114 .setMemRefs(VolLdMMO);
8115 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
8116 MBB->addSuccessor(LoopTestMBB);
8117
8118 // TailTestMBB
8119 // BRC DoneMBB
8120 // # fallthrough to TailMBB
8121 MBB = TailTestMBB;
8122 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
8123 .addReg(PHIReg)
8124 .addImm(0);
8125 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
8126 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_EQ)
8127 .addMBB(DoneMBB);
8128 MBB->addSuccessor(TailMBB);
8129 MBB->addSuccessor(DoneMBB);
8130
8131 // TailMBB
8132 // # fallthrough to DoneMBB
8133 MBB = TailMBB;
8134 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
8135 .addReg(SystemZ::R15D)
8136 .addReg(PHIReg);
8137 BuildMI(MBB, DL, TII->get(SystemZ::CG)).addReg(SystemZ::R15D)
8138 .addReg(SystemZ::R15D).addImm(-8).addReg(PHIReg)
8139 .setMemRefs(VolLdMMO);
8140 MBB->addSuccessor(DoneMBB);
8141
8142 // DoneMBB
8143 MBB = DoneMBB;
8144 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
8145 .addReg(SystemZ::R15D);
8146
8147 MI.eraseFromParent();
8148 return DoneMBB;
8149}
8150
8151SDValue SystemZTargetLowering::
8152getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
8153 MachineFunction &MF = DAG.getMachineFunction();
8154 auto *TFL =
8155 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
8156 SDLoc DL(SP);
8157 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
8158 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
8159}
8160
8161MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter(
8162 MachineInstr &MI, MachineBasicBlock *MBB) const {
8163 switch (MI.getOpcode()) {
8164 case SystemZ::Select32:
8165 case SystemZ::Select64:
8166 case SystemZ::SelectF32:
8167 case SystemZ::SelectF64:
8168 case SystemZ::SelectF128:
8169 case SystemZ::SelectVR32:
8170 case SystemZ::SelectVR64:
8171 case SystemZ::SelectVR128:
8172 return emitSelect(MI, MBB);
8173
8174 case SystemZ::CondStore8Mux:
8175 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
8176 case SystemZ::CondStore8MuxInv:
8177 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
8178 case SystemZ::CondStore16Mux:
8179 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
8180 case SystemZ::CondStore16MuxInv:
8181 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
8182 case SystemZ::CondStore32Mux:
8183 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
8184 case SystemZ::CondStore32MuxInv:
8185 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
8186 case SystemZ::CondStore8:
8187 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
8188 case SystemZ::CondStore8Inv:
8189 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
8190 case SystemZ::CondStore16:
8191 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
8192 case SystemZ::CondStore16Inv:
8193 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
8194 case SystemZ::CondStore32:
8195 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
8196 case SystemZ::CondStore32Inv:
8197 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
8198 case SystemZ::CondStore64:
8199 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
8200 case SystemZ::CondStore64Inv:
8201 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
8202 case SystemZ::CondStoreF32:
8203 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
8204 case SystemZ::CondStoreF32Inv:
8205 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
8206 case SystemZ::CondStoreF64:
8207 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
8208 case SystemZ::CondStoreF64Inv:
8209 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
8210
8211 case SystemZ::PAIR128:
8212 return emitPair128(MI, MBB);
8213 case SystemZ::AEXT128:
8214 return emitExt128(MI, MBB, false);
8215 case SystemZ::ZEXT128:
8216 return emitExt128(MI, MBB, true);
8217
8218 case SystemZ::ATOMIC_SWAPW:
8219 return emitAtomicLoadBinary(MI, MBB, 0, 0);
8220 case SystemZ::ATOMIC_SWAP_32:
8221 return emitAtomicLoadBinary(MI, MBB, 0, 32);
8222 case SystemZ::ATOMIC_SWAP_64:
8223 return emitAtomicLoadBinary(MI, MBB, 0, 64);
8224
8225 case SystemZ::ATOMIC_LOADW_AR:
8226 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
8227 case SystemZ::ATOMIC_LOADW_AFI:
8228 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
8229 case SystemZ::ATOMIC_LOAD_AR:
8230 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
8231 case SystemZ::ATOMIC_LOAD_AHI:
8232 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
8233 case SystemZ::ATOMIC_LOAD_AFI:
8234 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
8235 case SystemZ::ATOMIC_LOAD_AGR:
8236 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
8237 case SystemZ::ATOMIC_LOAD_AGHI:
8238 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
8239 case SystemZ::ATOMIC_LOAD_AGFI:
8240 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
8241
8242 case SystemZ::ATOMIC_LOADW_SR:
8243 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
8244 case SystemZ::ATOMIC_LOAD_SR:
8245 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
8246 case SystemZ::ATOMIC_LOAD_SGR:
8247 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
8248
8249 case SystemZ::ATOMIC_LOADW_NR:
8250 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
8251 case SystemZ::ATOMIC_LOADW_NILH:
8252 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
8253 case SystemZ::ATOMIC_LOAD_NR:
8254 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
8255 case SystemZ::ATOMIC_LOAD_NILL:
8256 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
8257 case SystemZ::ATOMIC_LOAD_NILH:
8258 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
8259 case SystemZ::ATOMIC_LOAD_NILF:
8260 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
8261 case SystemZ::ATOMIC_LOAD_NGR:
8262 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
8263 case SystemZ::ATOMIC_LOAD_NILL64:
8264 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
8265 case SystemZ::ATOMIC_LOAD_NILH64:
8266 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
8267 case SystemZ::ATOMIC_LOAD_NIHL64:
8268 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
8269 case SystemZ::ATOMIC_LOAD_NIHH64:
8270 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
8271 case SystemZ::ATOMIC_LOAD_NILF64:
8272 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
8273 case SystemZ::ATOMIC_LOAD_NIHF64:
8274 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
8275
8276 case SystemZ::ATOMIC_LOADW_OR:
8277 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
8278 case SystemZ::ATOMIC_LOADW_OILH:
8279 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
8280 case SystemZ::ATOMIC_LOAD_OR:
8281 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
8282 case SystemZ::ATOMIC_LOAD_OILL:
8283 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
8284 case SystemZ::ATOMIC_LOAD_OILH:
8285 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
8286 case SystemZ::ATOMIC_LOAD_OILF:
8287 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
8288 case SystemZ::ATOMIC_LOAD_OGR:
8289 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
8290 case SystemZ::ATOMIC_LOAD_OILL64:
8291 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
8292 case SystemZ::ATOMIC_LOAD_OILH64:
8293 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
8294 case SystemZ::ATOMIC_LOAD_OIHL64:
8295 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
8296 case SystemZ::ATOMIC_LOAD_OIHH64:
8297 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
8298 case SystemZ::ATOMIC_LOAD_OILF64:
8299 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
8300 case SystemZ::ATOMIC_LOAD_OIHF64:
8301 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
8302
8303 case SystemZ::ATOMIC_LOADW_XR:
8304 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
8305 case SystemZ::ATOMIC_LOADW_XILF:
8306 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
8307 case SystemZ::ATOMIC_LOAD_XR:
8308 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
8309 case SystemZ::ATOMIC_LOAD_XILF:
8310 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
8311 case SystemZ::ATOMIC_LOAD_XGR:
8312 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
8313 case SystemZ::ATOMIC_LOAD_XILF64:
8314 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
8315 case SystemZ::ATOMIC_LOAD_XIHF64:
8316 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
8317
8318 case SystemZ::ATOMIC_LOADW_NRi:
8319 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
8320 case SystemZ::ATOMIC_LOADW_NILHi:
8321 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
8322 case SystemZ::ATOMIC_LOAD_NRi:
8323 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
8324 case SystemZ::ATOMIC_LOAD_NILLi:
8325 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
8326 case SystemZ::ATOMIC_LOAD_NILHi:
8327 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
8328 case SystemZ::ATOMIC_LOAD_NILFi:
8329 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
8330 case SystemZ::ATOMIC_LOAD_NGRi:
8331 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
8332 case SystemZ::ATOMIC_LOAD_NILL64i:
8333 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
8334 case SystemZ::ATOMIC_LOAD_NILH64i:
8335 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
8336 case SystemZ::ATOMIC_LOAD_NIHL64i:
8337 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
8338 case SystemZ::ATOMIC_LOAD_NIHH64i:
8339 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
8340 case SystemZ::ATOMIC_LOAD_NILF64i:
8341 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
8342 case SystemZ::ATOMIC_LOAD_NIHF64i:
8343 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
8344
8345 case SystemZ::ATOMIC_LOADW_MIN:
8346 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
8347 SystemZ::CCMASK_CMP_LE, 0);
8348 case SystemZ::ATOMIC_LOAD_MIN_32:
8349 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
8350 SystemZ::CCMASK_CMP_LE, 32);
8351 case SystemZ::ATOMIC_LOAD_MIN_64:
8352 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
8353 SystemZ::CCMASK_CMP_LE, 64);
8354
8355 case SystemZ::ATOMIC_LOADW_MAX:
8356 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
8357 SystemZ::CCMASK_CMP_GE, 0);
8358 case SystemZ::ATOMIC_LOAD_MAX_32:
8359 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
8360 SystemZ::CCMASK_CMP_GE, 32);
8361 case SystemZ::ATOMIC_LOAD_MAX_64:
8362 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
8363 SystemZ::CCMASK_CMP_GE, 64);
8364
8365 case SystemZ::ATOMIC_LOADW_UMIN:
8366 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
8367 SystemZ::CCMASK_CMP_LE, 0);
8368 case SystemZ::ATOMIC_LOAD_UMIN_32:
8369 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
8370 SystemZ::CCMASK_CMP_LE, 32);
8371 case SystemZ::ATOMIC_LOAD_UMIN_64:
8372 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
8373 SystemZ::CCMASK_CMP_LE, 64);
8374
8375 case SystemZ::ATOMIC_LOADW_UMAX:
8376 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
8377 SystemZ::CCMASK_CMP_GE, 0);
8378 case SystemZ::ATOMIC_LOAD_UMAX_32:
8379 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
8380 SystemZ::CCMASK_CMP_GE, 32);
8381 case SystemZ::ATOMIC_LOAD_UMAX_64:
8382 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
8383 SystemZ::CCMASK_CMP_GE, 64);
8384
8385 case SystemZ::ATOMIC_CMP_SWAPW:
8386 return emitAtomicCmpSwapW(MI, MBB);
8387 case SystemZ::MVCSequence:
8388 case SystemZ::MVCLoop:
8389 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
8390 case SystemZ::NCSequence:
8391 case SystemZ::NCLoop:
8392 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
8393 case SystemZ::OCSequence:
8394 case SystemZ::OCLoop:
8395 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
8396 case SystemZ::XCSequence:
8397 case SystemZ::XCLoop:
8398 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
8399 case SystemZ::CLCSequence:
8400 case SystemZ::CLCLoop:
8401 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
8402 case SystemZ::CLSTLoop:
8403 return emitStringWrapper(MI, MBB, SystemZ::CLST);
8404 case SystemZ::MVSTLoop:
8405 return emitStringWrapper(MI, MBB, SystemZ::MVST);
8406 case SystemZ::SRSTLoop:
8407 return emitStringWrapper(MI, MBB, SystemZ::SRST);
8408 case SystemZ::TBEGIN:
8409 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
8410 case SystemZ::TBEGIN_nofloat:
8411 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
8412 case SystemZ::TBEGINC:
8413 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
8414 case SystemZ::LTEBRCompare_VecPseudo:
8415 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
8416 case SystemZ::LTDBRCompare_VecPseudo:
8417 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
8418 case SystemZ::LTXBRCompare_VecPseudo:
8419 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
8420
8421 case SystemZ::PROBED_ALLOCA:
8422 return emitProbedAlloca(MI, MBB);
8423
8424 case TargetOpcode::STACKMAP:
8425 case TargetOpcode::PATCHPOINT:
8426 return emitPatchPoint(MI, MBB);
8427
8428 default:
8429 llvm_unreachable("Unexpected instr type to insert");
8430 }
8431}
8432
8433// This is only used by the isel schedulers, and is needed only to prevent
8434// compiler from crashing when list-ilp is used.
8435const TargetRegisterClass *
8436SystemZTargetLowering::getRepRegClassFor(MVT VT) const {
8437 if (VT == MVT::Untyped)
8438 return &SystemZ::ADDR128BitRegClass;
8439 return TargetLowering::getRepRegClassFor(VT);
8440}
8441